Search code examples
c#asp.net-mvcmodel-view-controllerrouteshtml.actionlink

How to action link a route with several folders, not only controller and action?


I know I can action link a route like this:

 // GET: Home
    [Route("Home/About/{text}/{a}/{b?}/{c?}")]
    public ActionResult About(string text, string a, string b, string c)
    {
      ViewBag.Message = text + a + b + c;
      return View();
    }

by doing this:

@Html.ActionLink("GO", "About", "Home", new {text = "Test", a="value1",b="value2",c="value3" },null)

but what if I want to action link something like this?

 // GET: Home
    [Route("api/[controller]/[action]/{text}/{a}/{b?}/{c?}")]
    public ActionResult About(string text, string a, string b, string c)
    {
      ViewBag.Message = text + a + b + c;
      return View();
    }

Thanks in advance!


Solution

  • Add route name to your action:

     [Route("api/[controller]/[action]/{text}/{a}/{b?}/{c?}", Name ="AboutRoute")]
        public ActionResult About(string text, string a, string b, string c)
        {
          ViewBag.Message = text + a + b + c;
          return View();
        }
    

    and use the name :

    @Html.RouteLink("GO","AboutRoute", new {
                            text = "Test", 
                            a="value1",
                               b="value2",
                           c="value3" } )
    

    I tested it using Visual studio and it works properly.

    And by the way you call this action by 2 ways.

    1.Using Route Link and route name

    1. Using another input control or httpclient or ajax or postman by url .../api/..controllerName../..actionName../..route values...