Escaping the single quote character
In the code below, I'm building a string in my controller. In this string I use the single quote character. I need to protect this character before rendering it. First, I try something like L\'affaire but it doesn't work (because the quote character is already used in my helper, see below). I succeed with L& # 3 9;affaire (escape character for single quote, without spaces) but maybe there is a better way to proceed?
In my controller, I prepare a string like this:
var builderAnchor = new TagBuilder("a");
builderAnchor.MergeAttribute("href", "#");
builderAnchor.InnerHtml = "Annuler";
var builderText = new StringBuilder();
builderText.Append("L'affaire " + affaire.IdAffaire + " a été supprimée. ");
builderText.Append(builderAnchor);
sessionWrapper.Notification = new HtmlString(builderText.ToString());
Next, I have a helper called from a view like this:
public static IHtmlString ShowNotification(this HtmlHelper helper)
{
//...
returnedValue = "yellowNoti开发者_StackOverflowfication('" + helper.Encode(sessionWrapper.Notification) + "')";
return new HtmlString(returnedValue);
}
Finally, all of this stuff produce the html like below:
yellowNotification('L'affaire 12345 a été supprimée');
Thanks anyway.
I would recommend you using the JavaScriptSerializer class:
public static IHtmlString ShowNotification(this HtmlHelper helper)
{
//...
var serializer = new JavaScriptSerializer();
var value = serializer.Serialize(sessionWrapper.Notification);
returnedValue = string.Format("yellowNotification({0})", value);
return new HtmlString(returnedValue);
}
This will ensure that no matter what characters the Notification string contains it will be properly passed to the yellowNotification
function.
Also I don't quite understand what's the relation of the first code snippet you have shown to the second but what is sure that such code has no place in a controller.
精彩评论