Escaping single quote from an MVC 3 Razor View variable

让人想犯罪 __ 提交于 2019-12-04 03:20:30

问题


I have a variable within item.Name that contains the string "It's Tuesday!". To alleviate javascript errors, in the c# controller I have already escaped this single quote. On the webpage, it appears like this "It\'s Tuesday!".

This at least prevents any javascript errors, however, I do not want the actual string displayed to contain the backslash that has escaped it.

How might I be able to revert the escaping once the javascript errors have already been taken care of? This feels like a rather simple problem, but I am a bit unfamiliar with MVC 3. Any hint is much appreciated! My searching did not find me any example specific to this.

An example of my code in the Razor View:

@foreach (var item in Model)
{ 
    @Html.DisplayFor(modelItem => item.Name) // item.Name = "It\'s Tuesday!"
} 

回答1:


Create an extension method you can use or simply encode directly. I would not encode prior to the view getting it unless you have a separate property in your viewmodel meant for this (not a bad idea()

This is not tested but something along these lines


public static class HtmlExtensions

{
    public static IHtmlString JavaScriptEncode(this HtmlHelper html, string item)
    {
        return new HtmlString(HttpUtility.JavaScriptStringEncode(item));
    }
}

You can then just call @Html.JavaScriptEncode(yourProperty) from the view or simply reference your encoded property name.




回答2:


The following can be used to prevent encoding of the output again. This does however rely on you properly dealing with it yourself.

MVCHTMLString

@MvcHtmlString.Create(yourString)



回答3:


I prefer to make my views dumb. Therefore, I'd have a property called something like 'Display' or 'DisplayName' which handled the escaping for the view.



来源:https://stackoverflow.com/questions/8479260/escaping-single-quote-from-an-mvc-3-razor-view-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!