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?

1
  • There is related answer here and also here. Commented Jan 30, 2011 at 19:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

'id' should be 'genre' in the route default values.
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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.