Search code examples
c#asp.net-mvcrazorhtml-helper

Encode part of URL in Razor


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>

Solution

  • 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.