3

Scenario:- I have url in the following pattern:-

localhost:8080/albums/

routes.MapRoute(
{
  name: "AlbumHome",
  url : "Albums/{*albumName}"
  defaults: new {controller = "Albums", action="Index", albumName = ""}
}

Now in my action, I am getting the albumName from the DB, now how should I append the albumName in the url.

I want the url to be as:-

localhost:8080/albums/hindi
localhost:8080/albums/kanada
and so on.

Action

public ActionResult GetAlbumName()
{
  //get the albumName from db
   return RedirectToRoute("AlbumHome",albumName);
}

public ActionResult Index(string albumName)
{
   return view();
}

How to append this albumName in url?

2 Answers 2

2

You got it almost right!

There is an overload for RedirectToRoute which allows you to add route values as an object parameter. In your example it would look like this:

public ActionResult GetAlbumName()
{
  //get the albumName from db
   return RedirectToRoute("AlbumHome", new { albumName });
} 

You could also define your route more explicitly like this:

routes.MapRoute(
{
  name: "AlbumHome",
  url : "Albums/{albumName}"
  defaults: new {controller = "Albums", action="Index", albumName = UrlParameter.Optional }
}
Sign up to request clarification or add additional context in comments.

5 Comments

@thoaswr Ya I tried with that. but it rewrite url as localhost:8080/albums/?albumName=hindi I don't want the url to be such. It should be simple as localhost:8080/albums/hindi can you please tell me how to get this url in this pattern?
I tried your example and I did get the Url format you are aiming for. What version of MVC are you on? The name of the parameter in the url schema and the name of the property of the route values object have to match.
I am using MVC 4 if I do so, I get ** HTTP 404 Error**
Ok, maybe update your question's code snippets. It's all about the routes and the call to RedirectToRoute.
Yeah its rendering as desired. bit of configuration messed..but fixed now... Thank You.. :)
0
var context = new RequestContext(
    new HttpContextWrapper(System.Web.HttpContext.Current),
    new RouteData());
var urlHelper = new UrlHelper(context);
var url = urlHelper.Action("albumName", "Albums", null);
return Redirect(url);

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.