Search code examples
asp.net-mvcurlasp.net-mvc-4asp.net-mvc-routingactionlink

Generate semantic URL with asp.net mvc4 ActionLink in Razor views


I have a below setup in the controller for Public facing web page

Company -> About -> Partners ( which i want to be accessed as Company/About/Partners ) Action Method

public about(string category)
{
  ViewBag.Category = category;
  return View();
}

Generation of the link is done as below which is giving me the wrong URL

@Html.ActionLink("Partners & Investors", "About", "Company",new { Category = "Partners" },null)

Wrong Url

Company/About?Category=Partners%20and%20Investors

So the question is how does one generate the correct url that i wanted. What should i do ?


Solution

  • Urls will be generated automatically when you create new route and put it on correct position.

    Add

    Something like this:

    routes.MapRoute(
        "Category",
        "Company/About/{category}",
        new { controller = "Company", action = "About", category = "default" }
    );
    
    // default
    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    

    Also look at this link: Advanced Routing