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.