Asp.net mvc下拉列表给出空引用错误

本文关键字:引用 错误 net mvc 下拉列表 Asp | 更新日期: 2023-09-27 18:13:20

我正试图填充下拉列表,然后将其发布到数据库,但由于某种原因,它给出了错误,请建议。

控制器

 public class StudentController : BaseController
    {       
        private List<SelectListItem> _gendersList;
        [HttpGet]
        public ActionResult Create()
        {
            var model = new CreateStudent();
            _gendersList = new List<SelectListItem>()
            {
                 new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
                  new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
            };


            model.Genders = _gendersList;

            return View(model);
        }

        [HttpPost]
        public ActionResult Create(CreateStudent student)        
        {
            var result = true;
            _gendersList = new List<SelectListItem>()
            {
                 new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
                  new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
            };
            if (ModelState.IsValid)
            {
                result = _student.Insert(mappedStudent);
                if (result)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    TempData["Message"] = "Failed to create new student";
                    return View();
                }
            }
            return View("Create");
        }
    }
<<p> 视图/strong>
    @model CreateStudent
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-3.1.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<h2>Create</h2>
@{
    if (TempData["Message"] != null)
    {
        <h3>
            @TempData["Message"].ToString()
        </h3>
    }
}
@{ 

}
@using (Html.BeginForm("Create","Student",FormMethod.Post)) 
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.MiddleName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.MiddleName, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-4">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>     
        <div class="form-group">
            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">                              
                @*@Html.DropDownListFor(o=>o.Gender,Model.StudentGender, "", new { @class = "form-control" })*@
                @Html.DropDownListFor(o=>o.Gender,(List<SelectListItem>)Model.Genders,"1", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.IdNo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.IdNo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.IdNo, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.SchoolIdNo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.SchoolIdNo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SchoolIdNo, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ServiceType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ServiceType, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ServiceType, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Comments, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Comments, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Comments, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.IsEnabled, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.IsEnabled)
                    @Html.ValidationMessageFor(model => model.IsEnabled, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.FirstNameAr, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstNameAr, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstNameAr, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.MiddleNameAr, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.MiddleNameAr, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.MiddleNameAr, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.LastNameAr, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastNameAr, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastNameAr, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Asp.net mvc下拉列表给出空引用错误

你的视图是强类型的CreateStudent类和视图代码使用Model.Genders集合属性时,你使用DropDownListFor助手方法。但是在您的http post操作中,您在没有传递有效的CreateStudent对象的情况下调用return View()方法,并且在另一种情况下没有填充Genders属性。因此,当razor执行视图代码时,模型值是null(因为您没有向视图传递任何内容)

在将发布的视图模型返回给视图之前,您需要再次设置Genders属性。

[HttpPost]
public ActionResult Create(CreateStudent student)        
{ 
     var genderList = new List<SelectListItem>()
     {
          new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy}, 
          new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
     };
     if (ModelState.IsValid)
     {
        var result = _student.Insert(mappedStudent);
        if (result)
        {
            return RedirectToAction("Index");
        }
        else
        {
            student.Genders = genderList;
            TempData["Message"] = "Failed to create new student";
            return View(student);  // Passing the object here to view
        }
     }
     //Model validation fails. Return the same view
     student.Genders = genderList;
     return View(student);
    }
}

也不需要额外的强制转换。Model.Genders的类型为List<SelectListItem>

@Html.DropDownListFor(o=>o.Gender,Model.Genders, new { @class = "form-control" })