简体   繁体   中英

How to get optional parameters in mvc action C#

There is an TestAction in HomeController as below:

    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". Then DATA will be {c=23}, but not contain a and 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". (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. The model binder will read the query string and pass these parameter values to the action method.

/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. So after changes your method will look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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