下拉列表无效

时间:2012-05-12 23:00:25

标签: c# asp.net-mvc-3 drop-down-menu

控制器:

   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'

有什么想法?谢谢!

1 个答案:

答案 0 :(得分:1)

在您的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
)

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