且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVC3剃刀(下拉列表)

更新时间:2021-12-05 23:04:37

我怀疑你有你忘了重新分配视图的 CatList 属性POST操作模式使你得到NRE当您提交的形式,而不是当表单呈现初步:

I suspect that you have a POST action in which you forgot to reassign the CatList property of your view model so you are getting the NRE when you submit the form, not when the form is initially rendered:

public ActionResult DisplayCategory()
{
    var model = new CatModel();
    model.CatList = GetCat();
    return View(model);
}

[HttpPost]
public ActionResult Index(CatModel model)
{
    // some processing ...

    // since we return the same view we need to populate the CatList property
    // the same way we did in the GET action
    model.CatList = GetCat();
    return View(model);
}


private List<SelectListItem> GetCat()
{
    List<SelectListItem> itemList = new List<SelectListItem>();
    itemList.Add(new SelectListItem { Text = "1", Value = "1" });
    itemList.Add(new SelectListItem { Text = "2", Value = "2" });
    return itemList;
}