Escaping single quote from an MVC 3 Razor View variable

前端 未结 3 2026
执笔经年
执笔经年 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 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.

提交回复
热议问题