How to add string to url in asp.net mvc?

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

local: 8080 / albums /

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

      

Now in my action I am getting the album name from DB, now how do I add the album name to the url.

I want the url to be like this: -

localhost: 8080 / albums / hindi
localhost: 8080 / albums / kanada
etc.

Act

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

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

      

How to add this AlbumName to url?

+3


source to share


2 answers


You got it almost right!

There is an overload for RedirectToRoute

that allows you to add route values ​​as a parameter object

. In your example, it would look like this:

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

      



You can also define your route more clearly like this:

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

      

+2


source


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);

      



0


source







All Articles