1

With the following code in controller, I can pass the value of genre as "rock" with this url: "http://localhost:2414/Store/Browse?genre=rock"

public string Browse(string genre)
    {
        string message = HttpUtility.HtmlEncode("Store.Browse, Genre = "
    + genre);

        return message;
    }

I want to pass the same value of genre when the URL is "http://localhost:2414/Store/Browse/rock"

How can I do that?

Umair Khan Jadoon
  • 2,874
  • 11
  • 42
  • 63
  • There is related answer [here](https://stackoverflow.com/questions/488061/passing-multiple-parameters-to-controller-in-asp-net-mvc-also-generating-on-the) and also [here](https://stackoverflow.com/questions/155864/asp-net-mvc-problem-passing-parameters-to-the-controller). – Nuri YILMAZ Jan 30 '11 at 19:52

2 Answers2

5

First of all your controller action shouldn't look as it currently does. All controller actions should return an ActionResult and you shouldn't be HTML encoding parameters inside. That's the responsibility of the view:

public ActionResult Browse(string genre)
{
    string message = string.Format("Store.Browse, Genre = {0}", genre);
    // the cast to object is necessary to use the proper overload of the method
    // using view model instead of a view location which is a string        
    return View((object)message); 
}

and then in your view display and HTML encode like this:

<%= Html.DisplayForModel() %>

Now back to your question about handling urls like this. You could simply define the following route in your Global.asax:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{genre}",
    new { controller = "Home", action = "Index", genre = UrlParameter.Optional }
);

and then http://localhost:2414/Store/Browse/rock will invoke the Browse action on the Store controller passing rock as genre parameter.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

I want to correct one of the answers made above for the benefit of others;

"First of all your controller action shouldn't look as it currently does. All controller actions should return an ActionResult..."

Controller actions should return the most specific type based on what you are returning. E.g. If you are returning a Partial View, then use PartialViewResult, or if you are returning Json, then return a JsonResult. It is always best practice to return the most specific type, that way unit testing will be more accurate.

P.S Controller Actions can also return, Strings, Booleans etc..

davidferguson
  • 760
  • 5
  • 9