如何绑定URL参数,以不同名称的属性模型 [英] How to bind URL parameters to model properties with different names

查看:121
本文介绍了如何绑定URL参数,以不同名称的属性模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,可以说我有像这样一个URL,它通过HTTP动词 GET 来控制器动作我有以下映射:

Okay, lets say I have a URL like so, which is mapped via HTTP verb GET to the controller action I have below:

GET /foo/bar?sort=asc&r=true

如何绑定这我的模型酒吧在我控制器操作我有如下:

How can I bind this to my model Bar on my controller action I have below:

class Bar {
    string SortOrder { get; set; }
    bool Random { get; set; }
}

public ActionResult FooBar(Bar bar) {
    // Do something with bar
    return null;
}

请注意,该属性名不会也未必匹配URL参数的名称。另外,这些都是可选的URL参数。

Note that the property names won't and can't necessarily match the names of the URL parameters. Also, these are OPTIONAL url parameters.

推荐答案

模型绑定它从视图获取到您通过在名称的动作有模型中的参数,因此,如果匹配他们不匹配的绑定将无法工作。

The model binder matches the parameters it gets from the view to the model you have in the action by the Names, so if they won't match the binding will not work.

选项你有:


  1. 匹配输入名称的模特属性的名称...但你说你不能这样做,(一些未知的原因)。

  2. 编写定制模型绑定。 *

  3. 使用与preFIX的绑定属性 - 虽然它仍然会迫使你必须靠近模特属性名称输入名称

所以基本上,你不能这样做正是你想要的。

so basically, You can't do exactly what you want.

更新:

您在评论这些属性可以匹配参数名写的,所以不是写自定义属性,也许会成功做了绑定,只写一个视图模型(虚拟机fromMVC ...)来调整参数的URL的名称

You wrote in a comment that the properties CAN match the parameters names, so instead of write custom attributes that maybe will succeeded to do the binding, just write a ViewModel (The VM fromMVC...) to adjust the url parameters names.

编写自定义的模型绑定:

Writing custom model binder is not recommended by the MVC team:

在一般情况下,我们建议人们不要写自定义模型粘合剂,因为他们很难得到的权利和他们很少需要结果
  从这里

In general, we recommend folks don’t write custom model binders because they’re difficult to get right and they’re rarely needed
from here

这篇关于如何绑定URL参数,以不同名称的属性模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆