asp.net mvc SelectList设置selected失效及解决方案
在asp.net mvc的强类型视图(strongly typed view)使用下拉列表,在Controller中设定的选择项在View上选中失效
下面是我的代码:
public ActionResult Create(int id=0,int parentid=0) { var productCategory=db.ProductCategorys.Where(pc => pc.ParentID == parentid).ToList(); productCategory.Insert(0,new ProductCategoryModel() { Name = "顶级分类", ID = 0, ParentID = 0 }); ViewBag.ParentID = new SelectList(productCategory, "ID", "Name",id); return View(); }
View的代码:
<div class="editor-label"> @Html.LabelFor(model => model.ParentID) </div> <div class="editor-field"> @Html.DropDownList("ParentID",string.Empty) @Html.ValidationMessageFor(model => model.ParentID) </div>
注意上边我们的Model的属性叫ParentID,我们在使用SelectList
的时候是ViewBag.ParentID
,这没问题,不用给DropDownList指明了赋值,也能正常工作,但我们Url参数中出现了parentid就不会选中了,百思不得其解,把parentid修改成其他参数名称,结果能正常选中。
最近评论