0

I am having an issue whereby a NullReferenceException is thrown when I attempt to submit a form using ASP.NET MVC.

Herewith my model class:

public class TestModel
{
    [Required]
    public string SelectedItem { get; set; }

    public System.Web.Mvc.SelectList Items { get; set; }
}

The corresponding controller:

public class TestController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        var items = new List<SelectListItem>
        {
            new SelectListItem {Value = "1", Text = "Item 1"},
            new SelectListItem {Value = "2", Text = "Item 2"},
            new SelectListItem {Value = "3", Text = "Item 3"},
            new SelectListItem {Value = "4", Text = "Item 4"},
            new SelectListItem {Value = "5", Text = "Item 5"}
        };

        var model = new TestModel
        {
            Items = new SelectList(items, "Value", "Text")
        };

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(TestModel model)
    {
        if (!ModelState.IsValid)
        {
            // ...
            // ...
        }

        return View();
    }
}

And the view:

@model MyProject.Models.TestModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container">

    <h2>Title</h2>
    <hr />

    @Html.ValidationSummary()

    @using (Html.BeginForm("Index", "Test", FormMethod.Post, new { @class = "form-horizontal", id = "form" }))
    {
        <div class="form-group">
            @Html.LabelFor(m => m.SelectedItem):
            @Html.DropDownListFor(m => m.SelectedItem, Model.Items, new { @class = "form-control" })
        </div>

        <div class="form-group">
            <div class="col-sm-12 btn-toolbar">
                <button type="submit" class="btn btn-primary pull-right">Submit</button>
            </div>
        </div>
    }

</div>

This renders to the following:

Rendered view

When I click the submit button I get the following NullReferenceException:

Image of NullReferenceException

Any ideas what I might be missing?

RiaanDP
  • 1,212
  • 12
  • 18
  • 2
    Because `Model.Items` is null (your model is invalid and you return the view without reassigning the `Items` property) –  Nov 25 '15 at 10:11
  • @StephenMuecke Sorry, as I am new to ASP.NET I must be missing something - I set the model Items property in the Controller before passing the model to the View. What else do I need to do? – RiaanDP Nov 25 '15 at 10:22
  • 2
    Your return the view in the POST method if the model is invalid. You need to reassign `Items` just as you did in the GET method. –  Nov 25 '15 at 10:24
  • 1
    @StephenMuecke Thank you so much - yes that was it. I was focusing on the GET method and view all this time. I will mark your comment as the accepted answer if you post it as such. – RiaanDP Nov 25 '15 at 10:35
  • The question has been closed and I see no need to reopen it :) –  Nov 25 '15 at 10:37

0 Answers0