Home > Back-end >  ASP.NET MVC [FromForm] - Map into a record with different property names
ASP.NET MVC [FromForm] - Map into a record with different property names

Time:10-26

I guess this can be a pretty good question, however I have a feeling that the answer can be also pretty much simple.

So, let's suppose I have a HTTP POST endpoint which receives from an external source a form in the payload.

[HttpPost]
public ActionResult MyExample([FromForm] ExampleModel formModel)

My external source does not follow any standard naming convention, therefore, I can't rely on a simple equivalent "SerializerOptions". So, the solution now would be manually set the property name I'm receiving.

If I have a record ExampleModel, how could I set the property tag so that MVC [FromForm] magic mapping could handle it?

public record ExampleModel([property: ????] string MyProperty)

I can create a specific record or class with the exact name from the payload. That would be the easiest solution, but I'm trying to see if there is another way to not force my property to be wrongly named also.

CodePudding user response:

Apply a BindAttribute with a Prefix matching the name of the corresponding input element on the form.

Below example shows how the input value of a textbox named OtherName will be bound to MyProperty of the ExampleModel.

public record ExampleModel(
    [Bind(Prefix = "OtherName")] string MyProperty
    );

<form method="post">
    <input type="text" name="OtherName" />
    <input type="submit" />
</form>

CodePudding user response:

You can add the [FromForm] attribute to your record field definition like this:

public record ExampleModel([FromForm(Name="some nonstandard name with spaces")] string MyProperty)
  • Related