2013-05-15 125 views
0
[AllowAnonymous] 
    public ActionResult Register() 
    { 
     ViewBag.roleList = DALUser.GetRoleList(); 
     ViewBag.stateList = DALUser.GetStateList(); 
     return View(); 
    } 

<li> 
    @Html.LabelFor(m => m.role) 
    @Html.DropDownListFor(m => m.role, new SelectList(ViewBag.roleList, "Select Role")) 
</li> 

它会导致MVC 4 DropdownListfor错误

“值不能为空参数名:项目”。 roleList和stateList 只是字符串列表

任何人有一个想法呢?

+0

试试这个:new SelectList((列表 ViewBag.roleList,“Select Role”)) –

回答

1

一般来说,当您给SelectList构造函数一个空值时,您会看到该错误。您需要在ViewBag.roleList = DALUser.GetRoleList();上放置一个断点并验证除null之外的其他内容正在返回。请记住,IList对象的默认值是null

+0

好吧,列表项正确显示在下拉列表中。当我点击提交按钮时,它会导致错误。 – user1713153

+1

_“当我点击提交按钮时,它会导致错误。”_ - 你是否在“HttpPost”操作中重新填充ViewBag? – CodeCaster

+1

@ user1713153正如CodeCaster所暗示的,集合**不会**持久地存在于HTTP请求中,除非您在表单某处“隐藏”(这就是'ViewState'机制的工作方式)。请记住,MVC不是WebForms - 您需要重新创建任何未绑定到输入元素的数据。 DropDownList绑定到“选定值”属性,而不是集合。 –