Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC4 Model Not Binding

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:

enter image description here

like image 691
RMD Avatar asked Dec 20 '22 11:12

RMD


1 Answers

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/

like image 177
Filip W Avatar answered Dec 28 '22 12:12

Filip W