4

What is the proper way to encode a URL in Razor? My attempt below isn't changing the spaces into %20.

survey.Name is the variable passed to the controller

<a href="~/Survey/Take/@Uri.EscapeDataString(survey.Name)">@survey.Name</a>
4
  • What if you use @Html.Encode(survey.Name)
    – Hackerman
    Commented Oct 28, 2016 at 20:58
  • @Hackerman still doesn't encode it.
    – Tsukasa
    Commented Oct 28, 2016 at 21:00
  • @HttpUtility.UrlPathEncode(survey.Name) Commented Oct 28, 2016 at 21:06
  • @NagarajRaveendran nope still shows up with spaces.
    – Tsukasa
    Commented Oct 28, 2016 at 21:10

2 Answers 2

2

You can use Url.Encode like this:

@Html.ActionLink(survey.Name, "Take", "Survey", new { name = Url.Encode(survey.Name) }, new { })

As a side note, the link works without encoding the space. You would need to encode it when the link will be used outside your app, such as in an email.

2
  • So even when i click and hover over the link it will still show the spaces as which it is doing now because it's local and not external?
    – Tsukasa
    Commented Oct 28, 2016 at 23:00
  • @Tsukasa mine shows the spaces encoded when using Url.Encode(). My side note just meant that the link would still work with spaces. Commented Oct 29, 2016 at 3:07
1

HttpUtility.UrlPathEncode should work fine in your case. Tried and tested!

Here's a working fiddle example

<a href="~/Survey/Take/@HttpUtility.UrlPathEncode(survey.Name)">@survey.Name</a>

Update: (Thanks @Sam Rueby)

Do not use; intended only for browser compatibility. Use UrlEncode.

3
  • Description for this method states "Do not use; intended only for browser compatibility. Use UrlEncode".
    – Sam Rueby
    Commented Jul 20, 2018 at 20:06
  • Thanks.@SamRueby. Updated and added to answer. I havent seen that before, may the documentation was updated. Commented Jul 20, 2018 at 20:15
  • Sadly HttpUtility.UrlEncode still encodes spaces as +, and the now defunct UrlPathEncode doesn't encode # Commented Sep 24, 2018 at 2:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.