Designing the ViewModel Property to Use a Different Name for Binding

In MVC3, is there a way to decorate the ViewModel property to force DefaultModelBinder use a different name in the request?

For example, suppose you have the following presentation model:

 public class SomeModel { public string Direction {get;set;} } 

But the parameter included in it is Dir from an external source (for example, some third-party component, for example).

I know that a custom mediator can handle this, but I suppose there should be a way to decorate the property, just like action parameters can use Bind(Prefix="...") to determine this mapping.

+4
source share
3 answers

OK, therefore, after a more detailed study of similar questions and viewing feedback, it seems that the answer to my question is basically " NO ".

There is no ready-made way, so either custom binders should be used, or either properties should be renamed.

A similar question with a more detailed answer can be found here: How to associate URL parameters with model parameters with different names

+2
source

You can always create another property:

 public class SomeModel { public string Direction {get;set;} public string Dir { get { return this.Direction; } set { this.Direction = value; } } } 

I would also mention that the ViewModel used in the view (cshtml / vbhtml) does not have to be the same ViewModel used in the Post method.

+3
source

I was able to accomplish this in ASP.NET MVC Core using the FromForm attribute.

 public class DataTableOrder { public int Column { get; set; } [FromForm(Name = "Dir")] public string Direction { get; set; } } 

Documentation: https://docs.asp.net/en/latest/mvc/models/model-binding.html#customize-model-binding-behavior-with-attributes

However, if you are doing a GET or POST, you can use [FromQuery] instead of [FromForm] , I suppose.

0
source

All Articles