Escaping single quote from an MVC 3 Razor View variable

前端 未结 3 2027
执笔经年
执笔经年 2021-01-18 11:50

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 quot

相关标签:
3条回答
  • 2021-01-18 11:54

    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)
    
    0 讨论(0)
  • 2021-01-18 12:12

    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.

    0 讨论(0)
  • 2021-01-18 12:15

    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.

    0 讨论(0)
提交回复
热议问题