2013-0725

asp.net mvc SelectList设置selected失效及解决方案

作者: momy 分类: 编程开发 0 Comment »
摘要: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修改成其他参数名称,结果能正常选中。

标签: ASP.NET MVC SelectList selected 阅读: 11111
上一篇: ASP.NET MVC RedirectToAction跳转到其他Area - 20213次
下一篇: 常用正则表达式 - 9585次

向右滑动解锁留言