How to encode '/' in ASP.NET MVC Razor

Controller:

public ActionResult Tool(string id) { // Code goes here . . } 

View:

 <a href="/Home/@item.Type/@Url.Encode(item.Title)" id="toolTitleLink">@item.Title</a> 

From the above code, @item.Title can have special characters like '/' sample link http://localhost:39727/Home/Tool/C+Compiler+For+The+Pic10%2f12%2f16+Mcus when I trying to go to this link Tool Controller not called. I used @Url.Encode , but still the Controller not called.

+5
source share
1 answer

Unfortunately, even if you use System.Uri.EscapeDataString instead of Url.Encode as follows:

 <a href="/Home/@item.Type/@System.Uri.EscapeDataString(item.Title)" id="toolTitleLink">@item.Title</a> 

Slashes will be encoded on the rendering page (look in the page’s “view source”), the browser will still decrypt them.

You have two options, as far as I can see:

  • Use another character - make your own escape (so to speak;)) - for example, using the tilde (~) or something else a valid URL character you want to replace the slash.

  • Create a special route for action with for everyone at the end and analyze things from the action.

+2
source

All Articles