繁体   English   中英

Asp.net MVC DropdownList给出空引用错误

[英]Asp.net mvc DropdownList giving null reference error

我正在尝试填充一个dropdownlist,然后将其发布到db,但是由于某种原因它给出了错误,请提出建议。

控制者

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

视图

    @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")
}

当您使用DropDownListFor helper方法时,将视图强类型Model.Genders CreateStudent类,并且视图代码使用Model.Genders集合属性。 但是,在您的http post操作中,您将调用return View()方法而不传递有效的CreateStudent对象,在另一种情况下,则不填充Genders属性。 因此,当剃刀执行视图代码时,模型值为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" })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM