asp.net-mvcasp.net-mvc-5maproute

Change url asp.net mvc 5


routes.MapRoute(
            name: "MyRoute",
            url: "{Product}/{name}-{id}",
            defaults: new { controller = "Home", action = "Product", name = UrlParameter.Optional , id = UrlParameter.Optional }
        );

my routemap and i want my url in product action be like = http://localhost:13804/Wares/Product/name-id

but now is like = http://localhost:13804/Wares/Product/4?name=name


Solution

  • When defining a route pattern the token { and } are used to indicate a parameter of the action method. Since you do not have a parameter called Product in your action method, there is no point in having {Product} in the route template.

    Since your want url like yourSiteName/Ware/Product/name-id where name and id are dynamic parameter values, you should add the static part (/Ware/Product/) to the route template.

    This should work.

    routes.MapRoute(
        name: "MyRoute",
        url: "Ware/Product/{name}-{id}",
        defaults: new { controller = "Ware", action = "Product", 
                      name = UrlParameter.Optional, id = UrlParameter.Optional }
    );
    
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
    

    Assuming your Product action method accepts these two params

    public class WareController : Controller
    {
        public ActionResult Product(string name, int id)
        {
            return Content("received name : " + name +",id:"+ id);
        }
    }
    

    You can generate the urls with the above pattern using the Html.ActionLink helper now

    @Html.ActionLink("test", "Product", "Ware", new { id = 55, name = "some" }, null)