0

我在 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()
            });
4

1 回答 1

1

此错误的原因是因为在您的[HttpPost]操作中您忘记从数据库中重新填充CandidatesList视图模型上的属性。

[HttpPost]
public ActionResult Edit(EventEditVM model)
{
    if (ModelState.IsValid)
    {
        // the model is valid => do some processing here and redirect
        // you don't need to repopulate the CandidatesList property in 
        // this case because we are redirecting away
        return RedirectToAction("Success");
    }

    // there was a validation error => 
    // we need to repopulate the `CandidatesList` property on the view model 
    // the same way we did in the GET action before passing this model
    // back to the view
    model.CandidatesList = serviceCandidate
        .GetCandidates()
        .Select(x => new SelectListItem
        {
            Text = x.Nominative,
            Value = x.CandidateId.ToString()
        });

    return View(model);
}

不要忘记,当您提交表单时,只会将下拉列表的选定值发送到服务器。在您的 POST 控制器操作中,CandidatesListcollection 属性将为 null,因为它的值从未发送过。因此,如果您打算重新显示相同的视图,则需要初始化此属性,因为您的视图依赖于它。

于 2012-10-09T08:51:20.723 回答