Asp.net-Mvc
MVC4 DropDownListFor 對象引用未設置為對象的實例
我快要瘋了,試圖弄清楚這一點。我對 MVC 比較陌生,但對它已經很熟悉了。
我試圖在視圖上放置一個下拉列表,但在呼叫 DropDownListFor 的行上不斷收到“對象引用未設置為對象的實例”。這是我所擁有的:
模型
public class UserModel { public class DietObject { public int Id { get; set; } public string Name { get; set; } } public IEnumerable<DietObject> DietOptions = new List<DietObject> { new DietObject { Id = 0, Name = "Meat" }, new DietObject { Id = 1, Name = "Vegetarian" } }; [Required] [StringLength(15)] [Display(Name = "Diet:")] public string Diet { get; set; } }控制器
[HttpGet] public ActionResult Registration() { return View(); }看法
<div class="fHeader"> <%: Html.LabelFor(m => m.Diet) %> </div> <div class="fText"> <%: Html.DropDownListFor(m => m.Diet, new SelectList(Model.DietOptions, "Id", "Name", Model.DietOptions.First().Id))%> <%: Html.ValidationMessageFor(m => m.Diet)%> </div>錯誤
在頁面載入期間,它在此行出錯:
<%: Html.DropDownListFor(m => m.Diet, new SelectList(Model.DietOptions, "Id", "Name", Model.DietOptions.First().Id))%>有人把我從痛苦中解救出來。非常感激。
如果您想直接訪問
Model視圖中的屬性(在本例中為Model.DietOptions),那麼您需要在呼叫View控制器時傳入模型實例:[HttpGet] public ActionResult Registration() { return View(new UserModel()); }否則,你
Model會null得到一個空引用異常。