I have a very simple ASP.NET MVC4 page. It's rendering an edit form for the CustomerModel. The form displays correctly, but when I hit edit and post back, the model isn't being bound. Instead, all the properties of the CustomerModel are left at their defaults. Note that the correct controller method is being invoked, so that's not the issue.
I can see the form values with matching names to the model properties (Id, Name, Description), but the model doesn't have them set.
Ideas?
Here is the model:
public class CustomerModel
{
[Required]
public Guid Id;
[Required]
public string Name;
[Required]
public string Description;
}
And here is the relevant controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomerModel customerModel)
{
if (ModelState.IsValid)
{
//...Do stuff
return RedirectToAction("Index");
}
return View(customerModel);
}
Finally, here is a screen shot of the form collection with the populated values:
Your model has public fields but not public properties, these are not the same.
Change to:
public class CustomerModel
{
[Required]
public Guid Id {get; set;}
[Required]
public string Name {get; set;}
[Required]
public string Description {get; set;}
}
The default MVC model binder will work with properties, not fields.
More about this here - http://rightbrainleft.net/2011/02/default-mvc-model-binder-doesnt-like-fields/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With