我有一个带动作的控制器
public ActionResult ActionName(int ID)
{
ViewBag.StudentID = new SelectList(Student, "StudentID", "StudentName", ID);
return View()
}
在视图中
@Html.DropDownListFor(m => m.StudentID, ViewBag.StudentID as SelectList, "Select Student", new{ @class = ".."})
此字段是必填字段,剃须刀未使用所选值进行渲染且需求字段正在工作中但是当我使用时
@Html.DropDownList("StudentID", null, "Select Student", new{ @class = ".."})
剃刀渲染所选的值,该要求在上面的代码中不起作用
答案 0 :(得分:1)
您不能对model属性和ViewBag属性使用相同的名称。将其更改为(比方说)
ViewBag.StudentList = new SelectList(Student, "StudentID", "StudentName")
请注意,示例中的第4个参数不是必需的,因为它是确定所选内容的model属性的值。
并在视图中使用
@Html.DropDownListFor(m => m.StudentID, ViewBag.SelectList as SelectList, "Select Student", new{ @class = ".."})
如果是第一种方法(@Html.DropDownListFor()
),则不会选择该选项,因为在构建html之前,该方法会在内部构建新的IEnumerable<SelectListItem>
以设置Selected
属性。构建此代码时,它会在ViewDataDictionary
中为名称为StudentID
的密钥查找值,并找到一个System.Web.Mcv.SelectList
,但没有值为"System.Web.Mcv.SelectList"
的选项所以没有Selected = true
生成任何选项。
对于第二种方法(@Html.DropDownList()
),您提供null
作为第二个参数,因此帮助者在内部使用您的ViewBag
属性来生成选项,但现在您不能绑定到模型属性,因此帮助程序不会生成任何data-val-*
属性。