I have 4 model classes in my project. Every model class has an insert page. On every insert data page, I am getting the same error as System.NullReferenceException
. This error is showing in each of the @Html.EditorFor
attributes.
Suppose, I have 3 input attributes in my insert data page (.cshtml page), then every attribute shows the same error as System.NullReferenceException
. I can not understand why is this happening? Please see the attached image. I can not debug this because errors are showing in .cshtml pages. Please help I am going crazy with this error.
When I instantiated the model class in my method and passed it to the view page it worked. But now I am curious to know if such then why the methods built by Entity Framework do not instantiate the model classes and pass to view page.
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "UserId,UserName,Password,Department,LocalLvl,Status")] UserModel userModel)
{
if (ModelState.IsValid)
{
db.UserModels.Add(userModel);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userModel);
}
The above method was created by the Entity Framework scaffolding process, why not instantiated the model class. And before, my project was running successfully then suddenly it starts to show the error? Please help.
Expected that you had defined @model
at the top of your page which the page is expected to receive that type of object.
@model YourProject.Models.LoginModel
And make sure that you have returned an instance of the model to pass to your view. Otherwise, the @model
will be null
.
public ActionResult Login()
{
// Implementation
var model = new LoginModel();
return View(model);
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
// Implementation
return View(model);
}