Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net core model doesn't bind from form

I catch post request from 3rd-side static page (generated by Adobe Muse) and handle it with MVC action.

<form method="post" enctype="multipart/form-data">
   <input type="text" name="Name">
   ...
</form>

Routing for empty form action:

app.UseMvc(routes => routes.MapRoute(
   name: "default",
   template: "{controller=Home}/{action=Index}"));

But in according action I have model with every property is empty

Action:

[HttpPost]
public void Index(EmailModel email)
{
   Debug.WriteLine("Sending email");
}

Model:

public class EmailModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Company { get; set; }
    public string Phone { get; set; }
    public string Additional { get; set; }
}

Request.Form has all values from form, but model is empty

[0] {[Name, Example]}
[1] {[Email, [email protected]]}
[2] {[Company, Hello]}
[3] {[Phone, Hello]}
[4] {[Additional, Hello]}
like image 474
Kovpaev Alexey Avatar asked Oct 21 '16 08:10

Kovpaev Alexey


2 Answers

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 ){ ... }
like image 96
Stuart Avatar answered Sep 29 '22 00:09

Stuart


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.

like image 33
Velyo Avatar answered Sep 29 '22 01:09

Velyo