1

I have an Action Link that's as follows:

<td>@Html.ActionLink(item.InterfaceName, "Name", "Interface", new { name = item.InterfaceName}, null)</td>

item.InterfaceName is gathered from a database, and is FastEthernet0/0. This results in my HTML link being created to lead to "localhost:1842/Interface/Name/FastEthernet0/0". Is there a way to make "FastEthernet0/0" URL friendly so that my routing doesn't get confused?

MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89
blgrnboy
  • 4,877
  • 10
  • 43
  • 94

3 Answers3

3

You could work around this, by replacing the slash.

ActionLink(item.InterfaceName.Replace('/', '-'), ....)

After this your link would look like this: localhost:1842/Interface/Name/FastEthernet0-0. Naturally, your ActionMethod in your controller will misbehave, because it will expect a well named interface, so upon calling the method you need to revert the replace:

public ActionResult Name(string interfaceName)
{
   string _interfaceName = interfaceName.Replace('-','/');
   //retrieve information
   var result = db.Interfaces...

}

An alternative would be to build a custom route to catch your requests:

routes.MapRoute(
    "interface",
    "interface/{*id}",
     new { controller = "Interface", action = "Name", id = UrlParameter.Optional }
);

Your method would be:

public ActionResult Name(string interfaceName)
{
    //interfaceName is FastEthernet0/0

}

This solution was suggested by Darin Dimitrov here

Community
  • 1
  • 1
Marco
  • 22,856
  • 9
  • 75
  • 124
0

You probably have name as a part of the URL path in the route definition. Put it away and it will be sent like a URL parameter correctly, URL-encoded.

twoflower
  • 6,788
  • 2
  • 33
  • 44
0

You should use Url.Encode, because not just the "/" character, but others like "?#%" would broke in URLs too! Url.Encode replaces every character that needs to be encoded, here's a list of those:

http://www.w3schools.com/TAGs/ref_urlencode.asp

It would be a pretty big String.Replace to write a proper one for yourself. So use:

<td>@Html.ActionLink(item.InterfaceName, "Name", "Interface", new { name = Url.Encode(item.InterfaceName)}, null)</td>

Urlencoded strings are automatically decoded when passed as a parameter to the action method.

public ActionResult Name(string interfaceName)
{
    //interfaceName is FastEthernet0/0
}

item.InterfaceName.Replace('/', '-') is entirely wrong, for example "FastEthernet-0/0" would be passed as "FastEthernet-0-0" and decoded to "FastEthernet/0/0" which is wrong.

adhie
  • 274
  • 1
  • 9
  • If you encode a slash, and it is printed as a slash, it would still break the route. And in my little world, where I work with cisco devices, the OPs naming convention is the only valid. Could differ pending on the vendor, but I've never seen a differing naming scheme. – Marco Mar 03 '14 at 22:20