On MVC3, is there a way to decorate a ViewModel property in order to get the DefaultModelBinder to use a different name for it in the request?

For example, suppose you have the following view model:

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

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

I know a custom model binder could handle that, but I assume there must be a way to decorate the property, similar to the way action parameters can use Bind(Prefix="...") in order to define that mapping.

有帮助吗?

解决方案 2

OK, so after more research looking at similar questions and seeing the feedback here as well, it seems that the answer to my question is basically "NO".

There is no out-of-the-box way, so either custom binders must be used or or the properties should be renamed.

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

其他提示

You could always create another Property:

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

I'd also mention that the ViewModel used in a view (cshtml/vbhtml) does not have to be the same ViewModel used on the Post Method.

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, depending if you do a GET or a POST, you might want to use [FromQuery] instead of [FromForm] I suppose.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top