How to elegantly escape single and double quotes w

2019-06-06 10:59发布

问题:

This question already has an answer here:

  • Escaping a double-quote in inline c# script within javascript 3 answers

I have a C# string that needs to be passed to the page and then sent back to the server. It needs to be able to handle single quotes, double quotes and any other standard characters that might cause problems. I'm using MVC4 and razor. Right now I'm passing the string to javascript. I have something like this:

var str = '@Html.Raw(Model.SomeString.Replace("'", @"\'"))';

This works just fine but I was wondering if there's a better, more elegant way of escaping a C# string that will be passed to javascript.

I've already tried storing the value in a hidden field, like this:

@Html.Hidden(x => x.SomeString)

but then it has problems with double quotes when I go to grab the value.
EDIT: turns out the Html.Hidden issue was being caused by something else

Any help is greatly appreciated!

NOTE: must work in IE9 and 10. No ViewBags.

回答1:

You have to use HttpUtility.JavaScriptStringEncode. This is made for this exact purpose, it doesn't only encode quotes, but also escape sequences.

And BTW @Html.Hidden should work just fine because it also deals with escaping (a different kind than the above, HTML escaping in this case, dealing with ampersands, < >, etc).



回答2:

You can use HtmlEncode and the decode counterpart.

In javascript you'll have to do the same: HTML-encoding lost when attribute read from input field