我在 ASP.Net 中使用 MVC 3 我的 Web 应用程序是使用 ViewModel 和ViewModel builder设计的。
我使用 Builder 类在 ViewModel 中填充一些数据。就我而言,我有一个创建视图下拉列表,此代码工作正常。我的问题是在尝试创建编辑视图时,我收到此错误:
{"The ViewData item that has the key 'CandidateId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'."}
我的想法是用一些值填充 DropDownList ,但已经预先选择了一个作为数据库记录。
那么如何在编辑视图中显示下拉列表并从数据库中选择一个值?
看法
<div class="editor-label">
@Html.LabelFor(model => model.CandidateId)
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.CandidateId, Model.CandidatesList, "None")
</div>
查看模型
public Nullable<int> CandidateId { get; set; }
public IEnumerable<SelectListItem> CandidatesList;
查看模型构建器
// We are creating the SelectListItem to be added to the ViewModel
eventEditVM.CandidatesList = serviceCandidate.GetCandidates().Select(x => new SelectListItem
{
Text = x.Nominative,
Value = x.CandidateId.ToString()
});