Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL Routing: How do I have a string as my id?

I would like to receive a string as the id in the URL. Here is an example:

http://www.example.com/Home/Portal/Fishing

I would like to have Fishing in my id. But I cannot achieve it with the following code:

Code from my Controller:

public ActionResult Portal(string name)
{
    // some code
    ViewData["Portal Name"] = name;
}

Code from Global.asax.cs:

  routes.MapRoute(
  "Default", // Route name
  "{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
  );
like image 529
Gabriel Chung Avatar asked Feb 23 '23 12:02

Gabriel Chung


1 Answers

Just change the argument to id:

public ActionResult Portal(string id)
{
    // some code
    ViewData["Portal Name"] = id;
}

The argument will be bound if it has the same name as the route value token. So an alternate approach would be to keep the argument named name and change the route:

public ActionResult Portal(string name)
{
    // some code
    ViewData["Portal Name"] = name;
}

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{name}", // URL with parameters
    new { controller = "Home", action = "Index", name = UrlParameter.Optional } // Parameter defaults
);

I would choose using id, though, as it's the more standard approach.

like image 89
Craig Stuntz Avatar answered Mar 07 '23 18:03

Craig Stuntz