ASP.NET MVC DropDownListFor 选中项设置方法
在 ASP.NET MVC 中,可以使用SelectList 类来设置DropDownList 的选中项。
首先,确保在控制器中将选项列表传递给ViewBag。例如:
public ActionResult MyAction()
{
List<SelectListItem> typeList = new List<SelectListItem>
{
new SelectListItem { Text = 'Option 1', Value = '1' },
new SelectListItem { Text = 'Option 2', Value = '2' },
new SelectListItem { Text = 'Option 3', Value = '3' }
};
ViewBag.Type = typeList;
// 其他代码...
return View();
}
然后,在视图中使用Html.DropDownListFor 方法来生成下拉列表,并设置选中项的值。例如:
@Html.DropDownListFor(model => model.courseid, ViewBag.Type as List<SelectListItem>, new { style = 'width:50%', @class = 'form-control' })
在这个例子中,model.courseid 是将接收选中值的属性。要设置选中项,可以通过将courseid 的值赋给选项列表中的一个SelectListItem 的Selected 属性为true。例如:
public ActionResult MyAction()
{
List<SelectListItem> typeList = new List<SelectListItem>
{
new SelectListItem { Text = 'Option 1', Value = '1', Selected = false },
new SelectListItem { Text = 'Option 2', Value = '2', Selected = true },
new SelectListItem { Text = 'Option 3', Value = '3', Selected = false }
};
ViewBag.Type = typeList;
// 其他代码...
return View();
}
在这个例子中,'Option 2' 将被设置为默认选中项。
原文地址: https://www.cveoy.top/t/topic/pmjL 著作权归作者所有。请勿转载和采集!