问题
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