Asp.net core model doesn't bind from form

久未见 提交于 2019-12-02 23:11:42

Be careful not to give an action parameter a name that is the same as a model property or the binder will attempt to bind to the parameter and fail.

public async Task<IActionResult> Index( EmailModel email ){ ... }

public class EmailModel{ public string Email { get; set; } }

Change the actions parameter 'email' to a different name and it will bind as expected.

public async Task<IActionResult> Index( EmailModel uniqueName ){ ... }

I'm not sure it is same case, but I had same problem and nothing really looks to work for me.
The problem in my case was that I had a property called Model in my view model class

public string Model { get; set; }

When I renamed the property to ModelName everything was working fine again, even without FromForm attribute.

Looks like some special property names could be a bit of a problem for asp.net mvc model binding.

So, my advice is to check your model properties and maybe try renaming them one by one in order to check if the problem is there.

Hope this helps.

Change void to ActionResult.

[HttpPost]
public ActionResult Index(EmailModel email)

And don't forget verifying AntiForgeryToken from your view and action.

// to your form in view 
@Html.AntiForgeryToken()
// ------------

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(EmailModel email)

I'm having the same problem this docs helps me to understand Model Binding https://docs.asp.net/en/latest/mvc/models/model-binding.html

I solved my problem by making sure that the property name is exact match in form field name and I also add [FromForm] attribute to specify exactly the binding source.

This issue can also happen if one or more of your properties in the request model fail to bind into an acceptable on the request model.

In my case, I was supposed to pass a List<string> type to a property, but accidentally passed a string. This resulted in the entire request model becoming null

I ran into this today, and though in hindsight it seems obvious, just thought I'd add that you need to make sure your access modifiers for the Properties on the model you're binding are correct. I had public MyProperty { get; internal set; } on some and they would not bind. Removed internal and they worked just fine.

In my case, I was using the MVC 4.0 convention of naming the object you are posting. E.g.,

js: $http.post("SaveAnswer", { answer: answerValues })

C#: public ActionResult SaveAnswer([FromBody] AnswerVM answer) {...}

When I changed the js to $http.post("SaveAnswer", answerValues), everything works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!