0

This model is used to define a view:

namespace OnlineStore.ViewModels
{
    public class SubCategoryVM
    {
        [Key]
        public int ID { get; set; }
        [Required]
        public virtual string Name { get; set; }
        [Required(ErrorMessage = "Parent Category Name is required")]
        public virtual string ParentName { get; set; }
        public IEnumerable<SelectListItem> categoryNames { get; set; }
    }
}

Inside controller:

public ActionResult createSubCategory()
{
    SubCategoryVM model = new SubCategoryVM();
    var cNames = db.Categories.ToList();
    model.categoryNames = cNames.Select(x
        => new SelectListItem
        {
            Value = x.Name,
            Text = x.Name
        });
    return View(model);
}
[HttpPost]
public ActionResult createSubCategory(int? id, SubCategoryVM model)
{
    SubCategory sc = new SubCategory();
    if (ModelState.IsValid)
    {
        sc.ParentName = model.ParentName;
        sc.Name = model.Name;
    }
    return View();
}

and View:

@model OnlineStore.ViewModels.SubCategoryVM        

<div class="form-group">
            @Html.LabelFor(model => model.ParentName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.ParentName, Model.categoryNames, "--Please select an option--", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ParentName, "", new { @class = "text-danger" })
        </div>

This code is throwing a null-reference exception on line @Html.DropDownListFor(model => model.ParentName, Model.categoryNames, "--Please select an option--", new { @class = "form-control" }) saying:

Model.categoryName (Object reference not set to an instance of an object).

Please help me debug it.

Thanks in advance.

R K
  • 133
  • 12

1 Answers1

0

Problem is when you are posting the form and returning the View with the form data in case of invalid form, categoryNames in the model is becoming null and you have to repopulate the categoryNames before returning the view with model again.

So update your createSubCategory post method as follows:

[HttpPost]
public ActionResult createSubCategory(int? id, SubCategoryVM model)
{
    SubCategory sc = new SubCategory();
    if (ModelState.IsValid)
    {
        sc.ParentName = model.ParentName;
        sc.Name = model.Name;
    }

    var cNames = db.Categories.ToList();
    model.categoryNames = cNames.Select(x
        => new SelectListItem
        {
            Value = x.Name,
            Text = x.Name
        });

    return View(model);
}
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
  • Have to admit that I've done this for trillions of times, but always forget all about it. Thanks for the help. – R K Feb 04 '19 at 08:00