如何在MVC中将querystring映射到操作方法参数? [英] How to map querystring to action method parameters in MVC?

查看:139
本文介绍了如何在MVC中将querystring映射到操作方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个URL http://localhost/Home/DomSomething?t=123&s=TX,我想将此URL路由到以下操作方法

I have a url http://localhost/Home/DomSomething?t=123&s=TX and i want to route this URL to the following action method

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

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

since the query string names does not match with action method's parameter name, request is not routing to the action method.

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

If i change the url (just for testing) to http://localhost/Home/DomSomething?taxYear=123&state=TX then its working. (But i dont have access to change the request.)

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

I know there is Route attribute i can apply on the action method and that can map t to taxYear and s to state.

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

However i am not finding the correct syntax of Route attribute for this mapping, Can someone please help?

推荐答案

选项1

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

Option 1

If Query String parameters are always t and s, then you can use Prefix. Note that it won't accept taxYear and state anymore.

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,请声明所有参数,然后手动检查哪个参数具有值-

Option 2

If you want to accept both URLs, then declare all parameters, and manually check which parameter has value -

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.

Option 3

If you don't mind using third party package, you can use ActionParameterAlias. It accepts both URLs.

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
}

这篇关于如何在MVC中将querystring映射到操作方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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