MVC3 Razor (Drop Down List)

后端 未结 1 953
孤街浪徒
孤街浪徒 2021-01-27 15:25

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 abou

相关标签:
1条回答
  • 2021-01-27 16:02

    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;
    }
    
    0 讨论(0)
提交回复
热议问题