我快要疯了,试图弄清楚这一点。我是 MVC 的新手,但对它已经很熟悉了。
我试图在 View 上放置一个下拉列表,但在调用 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; }
}
Controller
[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))%>
有人让我摆脱痛苦。非常感激。
最佳答案
如果您想直接访问 View 中的 Model
属性(在这种情况下编写 Model.DietOptions
),那么您需要在 Controller 中调用 View
时传入模型实例:
[HttpGet]
public ActionResult Registration()
{
return View(new UserModel());
}
否则
Model
将是 null
并且您将获得 nullrefence excpetion。
关于asp.net-mvc - MVC4 DropDownListFor 对象引用未设置为对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21507753/