I got stuck on ModelState.IsValid in ASP.NET MVC

27 Views Asked by At

I get stuck on the ModelState.IsValid. I try to solve them from the other example, but it not worked. Could you guy help on me please?

This is my controller:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("DepartmentId,DepartmentName,LocationId")] Department department)
{
        if (ModelState.IsValid)
        {
            _context.Add(department);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        ViewData["LocationId"] = new SelectList(_context.Set<Location>(), "LocationId", "LocationId", department.LocationId);

        return View(department);
}
1

There are 1 best solutions below

3
Praveen Mishra On

Hi , Please use this code it will work.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("DepartmentId,DepartmentName,LocationId")] Department department)
{
    try
    {
        if (ModelState.IsValid)
        {
            _context.Add(department);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }
    catch (Exception ex)
    {
        // Handle any exceptions that occur during saving changes to the database
        ModelState.AddModelError(string.Empty, "An error occurred while saving the department.");
    }

    ViewData["LocationId"] = new SelectList(_context.Set<Location>(), "LocationId", "LocationId", department.LocationId);
    return View(department);
}