在 Razor 中编码 URL 的一部分
Encode part of URL in Razor
在 Razor 中编码 URL 的正确方法是什么?我下面的尝试没有将空格更改为 %20
.
survey.Name
是传递给controller的变量
<a href="~/Survey/Take/@Uri.EscapeDataString(survey.Name)">@survey.Name</a>
HttpUtility.UrlPathEncode 应该适用于您的情况。久经考验!
Here's a working fiddle example
<a href="~/Survey/Take/@HttpUtility.UrlPathEncode(survey.Name)">@survey.Name</a>
更新:(感谢@Sam Rueby)
Do not use; intended only for browser compatibility. Use UrlEncode.
您可以这样使用 Url.Encode:
@Html.ActionLink(survey.Name, "Take", "Survey", new { name = Url.Encode(survey.Name) }, new { })
附带说明一下,link 无需对 space 进行编码即可工作。当 link 将在您的应用程序外部使用时,例如在电子邮件中,您需要对其进行编码。
在 Razor 中编码 URL 的正确方法是什么?我下面的尝试没有将空格更改为 %20
.
survey.Name
是传递给controller的变量
<a href="~/Survey/Take/@Uri.EscapeDataString(survey.Name)">@survey.Name</a>
HttpUtility.UrlPathEncode 应该适用于您的情况。久经考验!
Here's a working fiddle example
<a href="~/Survey/Take/@HttpUtility.UrlPathEncode(survey.Name)">@survey.Name</a>
更新:(感谢@Sam Rueby)
Do not use; intended only for browser compatibility. Use UrlEncode.
您可以这样使用 Url.Encode:
@Html.ActionLink(survey.Name, "Take", "Survey", new { name = Url.Encode(survey.Name) }, new { })
附带说明一下,link 无需对 space 进行编码即可工作。当 link 将在您的应用程序外部使用时,例如在电子邮件中,您需要对其进行编码。