I am a beginner in asp.net core just started an EmployeeManagement project where Employee is my base class:
public class Employee
{
public int Id { get; set; }
[Required]
[Display(Name="First Name")]
public string Name { get; set; }
[Required]
[Display(Name="Official Email ID")]
[RegularExpression(@"^[a-zA-Z0-9_. -] @[a-zA-Z0-9-] \.[a-zA-Z0-9-.] $",
ErrorMessage = "Invalid email format")]
public string Email { get; set; }
public string Department { get; set; }
}
DropdownListModel is my second class which inherits from base class employee:
public class DropdownListModel:Employee
{
public SelectList Departmentcollection { get; set; }
}
Departmentcollection
is used to fill items in to a dropdownlist from database when I create a new employee.
<form asp-controller="home" asp-action="CreateEmp" method="post">
<div >
<div>
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name" ></span>
</div>
<div>
<label asp-for="Email"></label>
<input asp-for="Email" >
<span asp-validation-for="Email" ></span>
</div>
<div>
<label asp-for="Department"></label>
<select asp-for="Department"
[email protected] ></select>
</div>
<div>
<button type="submit" >Create</button>
</div>
[HttpPost]
public IActionResult CreateEmp(Employee emp)
{
if(!ModelState.IsValid)
{
return View();
}
Employee NewEmployee= repository.AddEmployee(emp);
return RedirectToAction("Details",new { Id = NewEmployee.Id });
}
[HttpGet]
public ViewResult CreateEmp()
{
return View (new DropdownListModel { Departmentcollection
= new SelectList(
repository
.employees.Select(d => d.Department).Distinct())
});
}
Code is working fine, dropdownlist is populating and records are inserting.
The problem is the validation is not working.
The error I am getting is:
An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Home_CreateEmp.<ExecuteAsync>b__19_0() in
CreateEmp.cshtml
[email protected] ></select>
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
What am I doing wrong?
I used virtual and override properties still same error.
services.AddControllersWithViews(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
CodePudding user response:
An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object.
NullReferenceException
is caused by the null object value. In your scenraio it is caused by [email protected]
from your detailed error message.
Assume that your backend code like below:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateEmp(DropdownListModel obj)
{
//do your stuff to add to database.....
return View(obj);
}
You can see your error message is caused in CreateEmp.cshtml
and you said the dropdownlist is populating at the first time. That is to say, your code must steps to the code return View(obj)
, under this situation it will post back to render the CreateEmp.cshtml
again and may cause some issue. You can debug your code to check your received model and find that there is no value for Departmentcollection
. Because <select asp-for="Department">
will send selected value to Department
property when form submit.
Above all, you need reset the dropdownlist value again before return view like below:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateEmp(DropdownListModel obj)
{
if(!ModelState.IsValid)
{
var data = new DropdownListModel()
{
Id = obj.Id,
Department = obj.Department,
Email = obj.Email,
Name = obj.Name,
Departmentcollection = new SelectList(repository.employees.Select(d => d.Department).Distinct())
};
return View(data);
}
Employee NewEmployee= repository.AddEmployee(emp);
return RedirectToAction("Details",new { Id = NewEmployee.Id });
}