当我尝试像这样使用 DropDownListFor() 时,我找不到为什么会出现 NullReferenceException 的答案:
看法:
<div class="form-group">
@Html.LabelFor(m => m.Category, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(
m => m.Category,
new SelectList(Model.CategoryOptionsList, "CategoryOptionId", "Value", Model.CategoryOptionsList.First().CategoryOptionId),
new { @class = "form-control" }
)
</div>
</div>
View 模型:
public class CategoryOption
{
public int CategoryOptionId { get; set; }
public string Value { get; set; }
}
public IEnumerable<CategoryOption> CategoryOptionsList = new List<CategoryOption>
{
new CategoryOption { CategoryOptionId = 0, Value="Rock" },
new CategoryOption { CategoryOptionId = 1, Value="Jazz" },
new CategoryOption { CategoryOptionId = 2, Value="Pop" },
new CategoryOption { CategoryOptionId = 3, Value="Metal" },
new CategoryOption { CategoryOptionId = 4, Value="Folk" }
};
[Required]
[Display(Name = "Kategoria")]
public string Category { get; set; }
最佳答案
我认为您忘记将 ViewModel 对象传递给您的 View ,请参见下文:
public ActionResult YourAction()
{
return View(new YourViewModel());
}
关于c# - NullReferenceException 在 ASP.NET MVC 5 中使用 DropDownListFor,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21740731/