我想使用DropDownListFor從模型中返回電子郵件列表。我在這個問題上發現了幾個主題,所以它似乎很常見,我認爲該列表需要重新填充,但是我找不到一種可行的方式(或者我理解其他示例的方式)。值不能爲空。參數名稱:DropDownListFor上的項目
無論我做什麼,我都會得到空錯誤。我在想,也許實際上它並沒有首先返回任何電子郵件,但我並不瞭解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) ....
嘗試通過「ViewBag .DropDownList「在Sele中ctList在你的剃鬚刀視圖中,而不是Model.EmailList – Nirman
@Nirman我實際上已經把它改成了'新的SelectList' ......真的是試錯了。編輯主帖以在剃鬚刀中添加ViewBag。 – kamil1995b
因爲'u.EmailList'是'null'(你沒有初始化它,更不用說用任何項目填充它) –