4

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

3
  • I don't see your AntiForgeryToken in there. Commented Jan 15, 2013 at 0:20
  • Where do you expect to see it? I have it in the view and I have the validate attribute on the method. Commented Jan 15, 2013 at 2:26
  • It has to be in your form, not just in your view. It has to be among the submitted form collection values. Commented Jan 15, 2013 at 2:32

1 Answer 1

11

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Ha! That was it. Probably never would have caught that. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.