Model Binding not working

后端 未结 10 1579
别那么骄傲
别那么骄傲 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: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!

提交回复
热议问题