Model Binding not working

后端 未结 10 1446
别那么骄傲
别那么骄傲 2021-02-06 01:52

I have the following POCO classes:

public class Location
    {
        public int LocationId { get; set; }
        public string Name { get; set; }
        publi         


        
相关标签:
10条回答
  • 2021-02-06 02:21

    Here's the problem:

    [HttpPost]
    public ActionResult Create(LocationViewModel location)
    

    Do you see it? It's the name of your action argument: location.

    Look at your view model now, it has a property named Location:

    public Location Location { get; set; }
    

    This confuses the model binder. It no longer knows whether you need to bind the LocationViewModel or its property.

    So simply rename to avoid the conflict:

    [HttpPost]
    public ActionResult Create(LocationViewModel model)
    
    0 讨论(0)
  • 2021-02-06 02:21

    Just to reiterate what Tod was saying, the model binder needs a 'name' attribute on the HTML element to map the properties. I was doing a quick test form by hand and only used the 'id' attribute to identify my elements.

    Everything fell into place when I added the 'name' attribute.

    <input type="text" id="Address" name="Address" />
    
    0 讨论(0)
  • 2021-02-06 02:23

    Let me add here yeat another reason why the model binder would not work properly.

    I had a model with the property ContactPhone, somewhere along the way I decided to change the name of this property to Phone, then all of a sudden model binding for this property stopped working when I was trying to create a new instance.

    The problem was on the Create action in my controller. I have used the default Visual Studio scaffolding and it has created the method signature as this:

    public ActionResult Create([Bind(Include = "Id,ContactPhone, ...")] Customer customer)
    { ... }
    

    Pay attention to the Bind attribute, the scaffolder created the fields using the original name ContactPhone and as this is a string, it was not refactored. As the new field Phone was not being included, it's value was ignored by the model binder.

    I hope this saves someone's time.

    Good luck!

    0 讨论(0)
  • 2021-02-06 02:26

    For anyone else still experiencing an issues with this, if you name your parameter in your post method to be the same as one of your properties, the default modelbinder will also fail.

    0 讨论(0)
提交回复
热议问题