在MVC视图JavaScript中转义字符

时间:2015-10-15 17:56:27

标签: javascript asp.net-mvc razor

我有这一行的页面:

  <input type="button" title="Join" value="Join" onclick="if(confirm('Are you sure you want to join @item.name.ToString() ?')) {location.href='@Url.Action("JoinTeam", "Team", new { id = item.id })'}" />&nbsp;

@item.name.ToString()中有一个单引号('),我需要逃避它。

当我查看原始HTML时,'&#39

2 个答案:

答案 0 :(得分:0)

正如您在Answer中看到的那样,在您的案例中使用@Html.Raw(jsString)

<input type="button" title="Join" value="Join" onclick="if(confirm('Are you sure you want to join @Html.Raw(item.name.ToString()) ?')) {location.href='@Url.Action("JoinTeam", "Team", new { id = item.id })'}" />&nbsp;

答案 1 :(得分:0)

您可以使用@Json.Encode来转义特殊字符:

<input type="button" title="Join" value="Join" 
    onclick="if(confirm('Are you sure you want to join @Json.Encode(item.name) ?')){location.href='@Url.Action("Home", "Index", new { id = item.id })'}" />