我尝试使用DropDownListFor从模型返回电子邮件列表。我在这个问题上找到了一些主题,所以它似乎很常见,我认为列表需要重新填充,但我找不到一种有效的方法(或者我对其他例子的理解方式) )。
无论我做什么,我总是得到null错误。我认为实际上它可能实际上并没有返回任何电子邮件,但我不理解dropdownlist与模型一起工作的方式。
是否存在导致null的不同问题,我现在无法看到?
我在一个类中定义列表:
public class User {
[Required]
[Display(Name = "Email Address")]
public string Email { get; set; }
public IEnumerable<SelectListItem> EmailList { get; set; }
}
控制器:
[HttpGet]
public ActionResult ChangeDetails()
{
var u = new User();
ViewBag.DropDownList = new SelectList(u.EmailList, "Email", "Email");
return View(u);
}
查看:
@Html.DropDownListFor(model => model.Email, (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---", new { htmlAttributes = new { @class = "form-control" } })
错误讯息:
Message: Value cannot be null. Parameter name: items
at System.Web.Mvc.MultiSelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, String dataGroupField, IEnumerable selectedValues, IEnumerable disabledValues, IEnumerable disabledGroups) ....
答案 0 :(得分:1)
尝试使用SelectListItem:
IList<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem()
{
Value = "Hello",
Text = "World"
});
ViewBag.DropDownList = lst;
或者:
var u = new User();
ViewBag.DropDownList = u.EmailList //You need to populate your EmailList first before you declare it here.
return View(u);
另一种选择是:
IList<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem()
{
Value = "Email",
Text = "Email"
});
ViewBag.DropDownList = new SelectList(p.EmailList, "Value", "Text");
并在你的观点上:
@Html.DropDownListFor(model => model.Email, (SelectList)ViewBag.DropDownList, "---Select a value---", new { htmlAttributes = new { @class = "form-control" } })