0

I am trying to populate a dropdownlist and then post it to db but for some reason it is giving error, please advice.

Controller

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

View

    @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")
}
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Shax
  • 4,207
  • 10
  • 46
  • 62
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Erik Philips Oct 16 '16 at 15:20

1 Answers1

0

Your view is strongly typed to a CreateStudent class and the view code is using Model.Genders collection property when you use the DropDownListFor helper method. But in your http post action, you are calling the return View() method without passing a valid CreateStudent object and in another case without populating the Genders property. So when razor executes the view code, the model value is null ( because you did not pass anything to the view)

You need to set the Genders property again before returning the posted view model back to the view.

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

Also there no need for an extra casting. Model.Genders is of type List<SelectListItem>

@Html.DropDownListFor(o=>o.Gender,Model.Genders, new { @class = "form-control" })
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • it worked but why my ModelState.IsValid is returning false and due to that i am unable to insert the student – Shax Oct 17 '16 at 06:17
  • finally i went through this place http://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor and it help and things are working fine. – Shax Oct 17 '16 at 06:35