ASP.NET MVC routing with one mandatory parameter and one optional parameter?

后端 未结 3 1928
南方客
南方客 2021-01-04 07:07

I\'ve been working on a large MVC application over the past month or so, but this is the first time I\'ve ever needed to define a custom route handler, and I\'m running into

3条回答
  •  天命终不由人
    2021-01-04 07:38

    Try this

    routes.MapRoute("MyRoute",
                     "myRoute/{param1 }/{param2 }",
                     new { controller = "MyController", action = "MyAction", param2 = UrlParameter.Optional },
                     new { param2 = @"\w+" });
    

    you can specify one parameter as optional by using "UrlParameter.Optional" and specified second one with DataType means if you pass integer value then DataType (@"\d+") and for string i have mention above.

    NOTE: Sequence of parameter is very important Optional parameter must pass at last and register your new route Before Default Route In Gloab.asax.

    then you action link like

    Test
    

    OR with one parameter

      Test
    

    In you Controller

     public ActionResult MyAction(string param2,string param1)
     {
       return View()
     }
    

提交回复
热议问题