0

控制器:

   OnePersonAllInfoViewModel vModel = new OnePersonAllInfoViewModel();
  vModel.PreferredContactType = new PreferredContactType();


ViewBag.PrefContactTypes = new SelectList(dbEntities.PreferredContactTypes
                                  .OrderBy(pct => pct.PreferredContactTypeID),
                                   "PreferredContactTypeID", "PreferredContactType1",
                                   vModel.PreferredContactType.PreferredContactTypeID);

看法:

<div class="editor-label">
        @Html.LabelFor(model => model.PreferredContactType.PreferredContactTypex)
    </div>

        @Html.DropDownListFor(model => model.PreferredContactType.PreferredContactTypeID, 
       ViewBag.PrefContactTypes as SelectList)

我在回发时收到此错误...没有“IEnumerable”类型的 ViewData 项目具有键“PreferredContactType.PreferredContactTypeID”

有什么想法吗?谢谢!

4

1 回答 1

1

在您的 HttpPost 控制器操作ViewBag.PrefContactTypes中,如果您重新显示相同的视图,则必须以与您在 GET 操作中相同的方式重新填充属性:

[HttpPost]
public ActionResult Process(OnePersonAllInfoViewModel model)
{
    ViewBag.PrefContactTypes = ...
    return View(model);
}

此外,您似乎已经定义了一些以 ViewModel 为后缀的类。这让读者相信您在您的应用程序和您使用的下一行中使用了视图模型ViewBag。为什么?为什么不充分利用视图模型及其强类型?

像这样:

public class OnePersonAllInfoViewModel
{
     public int PreferredContactTypeID { get; set; }
     public IEnumerable<PreferredContactType> PrefContactTypes { get; set; }
}

然后在您的 GET 操作中:

public ActionResult Index()
{
    var model = new OnePersonAllInfoViewModel();
    model.PrefContactTypes = dbEntities
        .PreferredContactTypes
        .OrderBy(pct => pct.PreferredContactTypeID)
        .ToList();
    return View(model);
}

然后是视图:

@Html.DropDownListFor(
    model => model.PreferredContactTypeID, 
    Model.PrefContactTypes
)

和 POST 动作:

[HttpPost]
public ActionResult Index(OnePersonAllInfoViewModel model)
{
    if (!ModelState.IsValid)
    {
        // the model is invalid => we must redisplay the same view =>
        // ensure that the PrefContactTypes property is populated
        model.PrefContactTypes = dbEntities
            .PreferredContactTypes
            .OrderBy(pct => pct.PreferredContactTypeID)
            .ToList();
        return View(model); 
    }

    // the model is valid => use the model.PreferredContactTypeID to do some
    // processing and redirect
    ...

    // Obviously if you need to stay on the same view then you must ensure that 
    // you have populated the PrefContactTypes property of your view model because
    // the view requires it in order to successfully render the dropdown list.
    // In this case you could simply move the code that populates this property
    // outside of the if statement that tests the validity of the model

    return RedirectToAction("Success"); 
}
于 2012-05-13T08:13:44.823 回答