I'm using database code first, so from database I create models (code-first from database).
After I created the models and dbcontext, I create controllers for each model (ASP.NET MVC 5 controller with views, using Entity Framework) so after controller is created, views like, index, create, details, edit, delete are automatically generated for that controller.
When I try to add any of my model to database using Create
action method, I get an exception.
Action method looks like this:
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RoleID,RoleName")] Role role)
{
if (ModelState.IsValid)
{
db.Roles.Add(role);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(role);
}
View looks like this:
<div class="form-horizontal">
<h4>Role</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.RoleName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.RoleName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.RoleName, "", 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-default" />
</div>
</div>
</div>
}
This line of code:
@Html.EditorFor(model => model.RoleName, new { htmlAttributes = new { @class = "form-control" } })
is causing this exception:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Can somebody tell me what I'm missing? I mean I didn't write a single line of code, it's all from scaffolding process... I don't know what is wrong