装饰在ViewModel属性上使用不同的名称进行绑定(Decoration on ViewModel property to use a different name for binding)

在MVC3上,有没有办法装饰ViewModel属性以使DefaultModelBinder在请求中使用不同的名称?

例如,假设您有以下视图模型:

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

但是来自外部源(例如某些第三方组件)的Dir参数。

我知道自定义模型绑定器可以处理它,但我认为必须有一种方法来装饰属性,类似于动作参数可以使用Bind(Prefix="...")的方式来定义该映射。

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.

最满意答案

您可以随时创建另一个属性:

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

我还要提到视图中使用的ViewModel(cshtml / vbhtml)不必与Post方法中使用的ViewModel相同。

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

更多推荐

参数,定义,Dir,public,电脑培训,计算机培训,IT培训"/> <meta name="description&