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!"
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With