我使用的是ASP RC1。
我正在使用的一个表单包含一个下拉列表,我已经用此代码将其放入了一个视图中。
<%= Html.DropDownList("areaid", (SelectList)ViewData["AreaId"], "Select Area Id")%>然而,当呈现时,我得到的是
<select id="areaid" name="areaid">
<option value="">Select Area Id</option>
<option value="1">Home</option>
...
</select> 我希望Select Area Id选项的值为0,并默认将其标记为选中,以便它与其他值一致,并且我可以验证某个区域是否已被选中,因为它是必需值。AreaId是一个整数,所以当我点击表单而没有接触下拉列表时,MVC抱怨"“不是整数,并给了我一个绑定错误。
那么,如何设置默认选项的值,然后使其在表单上处于选中状态呢?
谢谢,丹
发布于 2012-03-23 02:39:55
对于MVC3,SelectList有一个重载,您可以通过它定义选定的值。
Function Create() As ViewResult
ViewBag.EmployeeId = New SelectList(db.Employees, "Id", "Name", 1)
Return View()
End Function在本例中,我碰巧知道1是我想要的默认列表项的id,但假设您可以选择默认的via查询或其他任何东西
发布于 2015-03-30 18:59:08
您可以从控制器将"Select Area“数据添加到列表的第0个索引处,而不是传递视图中定义中的默认项。
这样,Select Area数据的索引值为0。
发布于 2017-10-04 14:37:15
我希望对多个下拉菜单使用相同的SelectList,并且不想在模型中重复该SelectList,所以我只添加了一个新的Html扩展方法,该方法接受一个值并设置选定的项。
public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper, string name, string value, IList<SelectListItem> selectList, object htmlAttributes)
{
IEnumerable<SelectListItem> items = selectList.Select(s => new SelectListItem {Text = s.Text, Value = s.Value, Selected = s.Value == value});
return htmlHelper.DropDownList(name, items, null /* optionLabel */, htmlAttributes);
}https://stackoverflow.com/questions/581805
复制相似问题