gsharp
gsharp

Reputation: 27937

Mapping naming convention for parameters in actions for asp.net core

I have a razor view with that does

 <form asp-action="Action">
 @Html.TextBoxFor(m => m.User.Name)
</form>

when submitting the form I would like to get the name of the user as a parameter, but with user, userName, user_Name the property doesnt get mapped.

What is asp.net core expecting as a name so that it gets mapped correctly?

public ActionResult Action(MyModel m) // not desired

public ActionResult Action(string name) // tried userName and user_Name
{

}

Upvotes: 1

Views: 462

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93143

The name of the input being generated in this scenario is User.Name. You can't call your parameter User.Name, of course, as this isn't a valid C# identifier. A simple way to make this work is to instruct the Model-Binder to use User.Name for your name parameter using the FromForm attribute. e.g.:

public ActionResult Action([FromForm(Name = "User.Name")] string name)
{

}

With this approach, name can be anything you like.

Upvotes: 4

Related Questions