Reputation: 6552
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>
Upvotes: 4
Views: 4880
Reputation: 5135
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.
Upvotes: 1
Reputation: 435
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.
Upvotes: 2