Asp.net mvc 3 MVC3剃须刀(下拉列表)

Asp.net mvc 3 MVC3剃须刀(下拉列表),asp.net-mvc-3,razor,Asp.net Mvc 3,Razor,我是MVC3剃须刀新手。目前,我面临这样一个错误“对象引用未设置为对象的实例。”,我不知道这是怎么回事 模型中 public List<SelectListItem> CatList { get; set; } [Display(Name = "Category")] public string CatID { get; set; } 公共列表CatList{get;set;} [显示(Name=“Category”)] 公共字符串CatID{get;se

我是MVC3剃须刀新手。目前,我面临这样一个错误“对象引用未设置为对象的实例。”,我不知道这是怎么回事

模型中

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

    [Display(Name = "Category")]
    public string CatID { get; set; }
公共列表CatList{get;set;}
[显示(Name=“Category”)]
公共字符串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;
    }
公共操作结果显示类别()
{
var模型=新的CatModel();
model.CatList=GetCat();
返回视图(模型);
}
私有列表GetCat()
{
List itemList=新列表();
添加(新建SelectListItem{Text=“1”,Value=“1”});
添加(新建SelectListItem{Text=“2”,Value=“2”});
返回项目列表;
}
在CSHTML中

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

    </table>
}
@使用(Html.BeginForm())
{
@LabelFor(c=>c.CatID)
@DropDownListFor(c=>c.CatID,Model.CatList)
}

感谢您的帮助。

我怀疑您有一个POST操作,其中您忘记重新分配视图模型的
CatList
属性,因此您在提交表单时获得了NRE,而不是在表单最初呈现时:

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;
}
公共操作结果显示类别()
{
var模型=新的CatModel();
model.CatList=GetCat();
返回视图(模型);
}
[HttpPost]
公共行动结果指数(CatModel)
{
//一些处理。。。
//由于返回相同的视图,因此需要填充CatList属性
//和我们在GET行动中做的一样
model.CatList=GetCat();
返回视图(模型);
}
私有列表GetCat()
{
List itemList=新列表();
添加(新建SelectListItem{Text=“1”,Value=“1”});
添加(新建SelectListItem{Text=“2”,Value=“2”});
返回项目列表;
}

您可以发布堆栈跟踪结果吗?哪一行引发异常?@Html.DropDownListFor(c=>c.CategoryID,Model.CategoryTypeList)给出了错误它还说用户代码未处理NullReferenceException。什么是
Model.CategoryTypeList
?在你发布的代码中没有它的迹象。。。您只有
CatList
。。。请编辑您关于
Model.CategoryTypeList
的问题,因为异常告诉您
Model.CategoryTypeList
null
我刚刚将您的代码放入解决方案中,效果很好。我在想,除了你在这里所展示的以外,还有别的事情正在发生。