Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping single quote from an MVC 3 Razor View variable

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!"
} 
like image 909
mherr Avatar asked Dec 12 '11 18:12

mherr


1 Answers

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.

like image 73
Adam Tuliper Avatar answered Oct 13 '22 02:10

Adam Tuliper