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>
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.
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.
@Html.Encode(survey.Name)