I'm working with ASP.NET Core MVC 5.0 in Visual Studio 2019. I had the scaffolder generate a controller with CRUD operations using Entity Framework Core. I see that there are two Edit() methods, the GET version of the method looks up the entity in the database and passes it to the Edit view. So far, everything makes sense. What I'm a bit confused about is the POST version of the Edit() method. This is what its signature and first statement look like:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] Department department)
{
if (id != department.Id)
{
return NotFound();
}
// ... (Removed for brevity)
}
If the ID can be bound to the Department entity using model binding, why does it require the first int id as parameter? I have tried removing it along with the equality check and the edit still works. I have also noticed a hidden input type in my Edit view:
<input type="hidden" asp-for="Id" />
which I tried removing as well after removing the id parameter. The Edit() somehow still works. I would like to know the purpose of the ID parameter, the equality check id == department.Id in the Edit() method and the hidden input field in the Edit view.
I actually wanted to use a viewmodel instead of using my entity directly with BindAttribute but ran into this confusion.
My entity is called Department and it looks like this:
public class Department
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "{0} is required")]
[StringLength(maximumLength: 100, MinimumLength = 1, ErrorMessage = "{0} should be between {2} and {1} characters")]
public string Name { get; set; }
public List<Course> Courses { get; set; }
}
For more context, here's what the GET version of Edit() looks like:
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var department = await _context.Departments.FindAsync(id);
if (department == null)
{
return NotFound();
}
return View(department);
}


