1

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Jamshaid K. Jun 09 '20 at 23:36
  • Try passing the newly initialized model to the `View()` method in Create Controller. – Jamshaid K. Jun 09 '20 at 23:38

2 Answers2

1

When you first call the create method

public ActionResult Create

it returns to the Create view without a model, that's why you got a NullReferenceException (I guess the view you post is update view).

Change your view and not using model => model.RoleName, the right way of create view:

@model XX.Models.Role
<h4>Role</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="RoleName" class="control-label"></label>
                <input asp-for="RoleName" class="form-control" />
                <span asp-validation-for="RoleName" class="text-danger"></span>
            </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>
        </form>
    </div>
</div>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Michael Wang
  • 3,782
  • 1
  • 5
  • 15
0

You should pass an instance of Role class to Create view

public ActionResult Create()
{
    return View(new Role() { });
}
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41