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:
When I click the submit button I get the following NullReferenceException:
Any ideas what I might be missing?