在MVC中,可以通过以下步骤动态添加时将Dropdownlist的值设置为每行的Textboxfor:
以下是一个示例代码:
在控制器中:
public ActionResult Index()
{
List<SelectListItem> dropdownListData = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Option 1" },
new SelectListItem { Value = "2", Text = "Option 2" },
new SelectListItem { Value = "3", Text = "Option 3" }
};
ViewBag.DropdownListData = dropdownListData;
return View();
}
在视图中:
@model List<YourModel>
@{
int rowNumber = 0;
}
@foreach (var item in Model)
{
<div>
@Html.DropDownListFor(model => model[rowNumber].DropdownlistValue, (IEnumerable<SelectListItem>)ViewBag.DropdownListData, "Select an option")
@Html.TextBoxFor(model => model[rowNumber].TextboxValue)
</div>
rowNumber++;
}
<script>
$(document).ready(function () {
$('select').change(function () {
var selectedValue = $(this).val();
var textbox = $(this).siblings('input[type="text"]');
textbox.val(selectedValue);
});
});
</script>
在上述示例中,我们首先在控制器中创建了一个包含Dropdownlist的数据源(dropdownListData),并将其传递给视图(ViewBag.DropdownListData)。然后,在视图中使用foreach循环遍历每一行数据,并为每一行创建一个Dropdownlist和一个Textboxfor。Dropdownlist的数据源绑定到ViewBag.DropdownListData,并为每个Textboxfor设置一个唯一的名称。最后,使用JavaScript或jQuery来实现当Dropdownlist的值改变时,将对应的Textboxfor的值设置为Dropdownlist的选中值。
请注意,上述示例中的代码仅供参考,具体实现可能会根据你的实际需求和数据模型而有所不同。
领取专属 10元无门槛券
手把手带您无忧上云