使用DropDownListFor时提交ASP.NET MVC表单的NullReferenceException

时间:2015-11-25 10:08:27

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我遇到一个问题,当我尝试使用ASP.NET MVC提交表单时会抛出NullReferenceException。

这是我的模特课:

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

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

相应的控制器:

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

观点:

@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>

这将呈现以下内容:

Rendered view

当我单击提交按钮时,我得到以下NullReferenceException:

Image of NullReferenceException

我可能缺少什么想法?

0 个答案:

没有答案