MVC3剃刀(下拉列表) [英] MVC3 Razor (Drop Down List)

查看:171
本文介绍了MVC3剃刀(下拉列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对MVC3剃刀新。目前,我面对这个错误对象引用未设置到对象的实例。,这我不知道这是什么的。

I'm new towards MVC3 Razor. Currently, I'm facing this error "Object reference not set to an instance of an object.", which I have no idea what is this about.

在型号

    public List<SelectListItem> CatList { get; set; }

    [Display(Name = "Category")]
    public string CatID { get; set; }

在控制器

    public ActionResult DisplayCategory()
    {
        var model = new CatModel();
        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;
    }

在CSHTML

@using (Html.BeginForm())
{
    <table>
    <tr>
    <td>@Html.LabelFor(c => c.CatID)</td>
    <td>@Html.DropDownListFor(c => c.CatID, Model.CatList)</td>
    </tr>

    </table>
}

感谢您的帮助。

推荐答案

我怀疑你有你忘了重新分配视图的 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;
}

这篇关于MVC3剃刀(下拉列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆