0
votes

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.

In Model

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

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

In Controller

    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;
    }

In CSHTML

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

    </table>
}

Thanks for any help.

1
Can you post the stack trace what you get? Which line throws the exception? - nemesv
@Html.DropDownListFor(c => c.CategoryID, Model.CategoryTypeList) is giving the error - USER_ME
It also says NullReferenceException was unhandled by user code. - USER_ME
What is Model.CategoryTypeList? In your posted code there is no sign of it... you only have CatList... please edit your question about Model.CategoryTypeList because the exception tells you that Model.CategoryTypeList is null - nemesv
I just put your code into a solution and it works just fine. I'm thinking something else is going on besides what you have shown here. - Josh

1 Answers

1
votes

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;
}