Biki
Biki

Reputation: 2588

How to generate custom URL in MVC3, instead of passing my parameters as query string

When I type the URL like ../Search/Recipes/Deserts/Pie, I can get redirected to that page (i.e in SearchController, action method would be Recipes & parameters would be Deserts & Pie .

NB: To achieve the same I ve added a route in my Global.asax, that looks like :

    routes.MapRoute(
            "SearchRecipes",                                              
            "Search/Recipes/{category}/{type}",                           
            new { controller = "Search", action = "Recipes", category = "all" , type = ""}  
 );

But how to generate that URL through our code? When I try to add a route value in Url.Action, it comes as a query string.

For example,

Url.Action( "Recipes" , "Search" , new { type = item.type, isPie = item.isPie} )

would give me link that looks like : Search/Recipes?type=Deserts&isPie=Y,

but I want to generate url like Search/Recipes/Deserts/Y.

Please let me know how we can achieve the same?

Basically I dont want to pass my parameters as query string, but want to adhere to \ separated values.

Upvotes: 0

Views: 1449

Answers (2)

scartag
scartag

Reputation: 17680

You can use the UrlHelper.RouteUrl method

Url.RouteUrl("SearchRecipes", new {category = item.category, type=item.type});

Upvotes: 0

MikeSW
MikeSW

Reputation: 16378

Try

 routes.MapRoute(
        "SearchRecipes",                                              
        "Search/Recipes/{category}/{type}/{isPie}",                           
        new { controller = "Search", action = "Recipes", category = "all" , type = "", isPie="N"}  
  );
@Url.RouteUrl("SearchRecipes",new{category=item.Category,type=item.type,isPie=itme.isPie})

Any query parameter not specified when defining a route will be added as ?param=value

Upvotes: 1

Related Questions