簡體   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