加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何将查询字符串映射到MVC中的操作方法参数?

发布时间:2020-12-16 03:35:33 所属栏目:asp.Net 来源:网络整理
导读:我有一个网址http:// localhost / Home / DomSomething?t = 123 s = TX我想将此网址路由到以下操作方法 public class HomeController{ public ActionResult DoSomething(int taxYear,string state) { // do something here }} 由于查询字符串名称与操作方
我有一个网址http:// localhost / Home / DomSomething?t = 123& s = TX我想将此网址路由到以下操作方法

public class HomeController
{
   public ActionResult DoSomething(int taxYear,string state)
   {
      // do something here
   }
}

由于查询字符串名称与操作方法的参数名称不匹配,因此请求不会路由到操作方法.

如果我将网址(仅用于测试)更改为http:// localhost / Home / DomSomething?taxYear = 123& state = TX则其工作正常. (但我没有权限更改请求.)

我知道我可以在动作方法上应用Route属性,并且可以将t映射到taxYear和s to state.

但是,我没有为此映射找到Route属性的正确语法,有人可以帮忙吗?

解决方法

选项1

如果查询字符串参数始终为t和s,则可以使用前缀.请注意,它不再接受taxYear和state.

http://localhost:10096/home/DoSomething?t=123&s=TX

public ActionResult DoSomething([Bind(Prefix = "t")] int taxYear,[Bind(Prefix = "s")] string state)
{
    // do something here
}

选项2

如果要接受这两个URL,则声明所有参数,并手动检查哪个参数具有值 –

http://localhost:10096/home/DoSomething?t=123&s=TX
http://localhost:10096/home/DoSomething?taxYear=123&state=TX

public ActionResult DoSomething(
    int? t = null,int? taxYear = null,string s = "",string state = "")
{
    // do something here
}

选项3

如果您不介意使用第三方软件包,则可以使用ActionParameterAlias.它接受这两个URL.

http://localhost:10096/home/DoSomething?t=123&s=TX
http://localhost:10096/home/DoSomething?taxYear=123&state=TX

[ParameterAlias("taxYear","t")]
[ParameterAlias("state","s")]
public ActionResult DoSomething(int taxYear,string state)
{
    // do something here
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读