下拉列表不起作用

本文关键字:不起作用 下拉列表 | 更新日期: 2023-09-27 18:33:55

>Controller:

   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 项具有键"首选联系人类型。首选联系人类型 ID"

有什么想法吗?谢谢!

下拉列表不起作用

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

[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
)

和开机自检操作:

[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"); 
}