How to add required field in Asp.net MVC Core.
Add.cshtml
<form method="post" asp-action="Add" class="mt-5">
<div class="mb-3">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<label asp-for="Name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" asp-for="Name" >
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Model
public class Employee
{
[Key]
public Guid Id { get; set; }
[Required(ErrorMessage = "Name is required.")]
public string? Name { get; set; }
}
Controller
[HttpPost]
public async Task<IActionResult> Add(AddEmployeeView addEmployeeRequest)
{
if (ModelState.IsValid)
{
var employee = new Employee()
{
Id = Guid.NewGuid(),
Name = addEmployeeRequest.Name
};
await mvcDemoDbContext.Employees.AddAsync(employee);
await mvcDemoDbContext.SaveChangesAsync();
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
I have tried as above but it is not working.