简体   繁体   English

如何在MVC动作C#中获得可选参数

[英]How to get optional parameters in mvc action C#

There is an TestAction in HomeController as below: 在HomeController中有一个TestAction,如下所示:

    public ActionResult TestAction(string a = "a", int b = 2, int c = 1)
    {
        var DATA = Request.Params;//Can't get param neither a nor b
        return View();
    }

If my visit link is "/Home/TestAction?c=23". 如果我的访问链接是“ / Home / TestAction?c = 23”。 Then DATA will be {c=23}, but not contain a and b. 然后,DATA将为{c = 23},但不包含a和b。 Does there any way to get these two params to make DATA like {a="a", b=2, c=23} by visit link "/Home/TestAction?c=23". 是否有任何方法可以通过访问链接“ / Home / TestAction?c = 23”来获取这两个参数以制作像{a =“ a”,b = 2,c = 23}这样的数据。 (These params are different in different page, so can't hard-code). (这些参数在不同的页面中是不同的,因此不能硬编码)。

You can do it by passing the params in the url as following. 您可以通过按如下所示在url中传递参数来实现。 The model binder will read the query string and pass these parameter values to the action method. 模型绑定程序将读取查询字符串,并将这些参数值传递给action方法。

/Home/TestAction?a=valuea&b=valueb

You can also use the route data to pass the value. 您也可以使用路线数据来传递值。 An appropriate route will need to be defined to do that. 为此,需要定义一条适当的路线。

Take all the paramters as nullable int?, string accepts null by default. 将所有参数作为可为null的int ?,字符串默认情况下接受null。 So after changes your method will look like 因此,更改后,您的方法将如下所示

public ActionResult TestAction(string a, int? b, int? c)
{
   //Check conditions for null here
    return View();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM