Search code examples
asp.net-mvcroutesasp.net-mvc-routing

How to display only name in url instead of id in mvc.net using routing


I am getting url like http://localhost:49671/TestRoutes/Display?f=hi&i=2

I want it like http://localhost:49671/TestRoutes/Display/hi

I call it from Index method.

[HttpPost]
public ActionResult Index(int? e )
{
    //  return View("Display", new { f = "hi", i = 2 });
    return RedirectToAction("Display", new { f = "hi", i = 2 });
}

Index view

@model Try.Models.TestRoutes
@using (Html.BeginForm())
{
    Model.e = 5 ; 
    <input type="submit" value="Create" class="btn btn-default" />
}

Display Action method

// [Route("TestRoutes/{s}")]
public ActionResult Display(string s, int i)
{
    return View(); 
}

Route config file

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        "Professional", // Route name
        "{controller}/{action}/{id}/{name}", // URL with parameters
         new { controller = "TestRoutes", action = "Display", s = UrlParameter.Optional, i = UrlParameter.Optional
    });
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id =   UrlParameter.Optional
    });

Solution

  • You need to change your route definition to

    routes.MapRoute(
        name: "Professional",
        url: "TestRoutes/Display/{s}/{i}",
        default: new { controller = "TestRoutes", action = "Display", i = UrlParameter.Optional }
    );
    

    so that the names of the placeholders match the names of the parameters in your method. Note also that only the last parameter can be marked as UrlParameter.Optional (otherwise the RoutingEngine cannot match up the segments and the values will be added as query string parameters, not route values)

    Then you need to change the controller method to match the route/method parameters

    [HttpPost]
    public ActionResult Index(int? e )
    {
        return RedirectToAction("Display", new { s = "hi", i = 2 }); // s not f
    }