How to elegantly escape single and double quotes w

2019-06-06 10:28发布

This question already has an answer here:

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.

2条回答
等我变得足够好
2楼-- · 2019-06-06 11:19

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).

查看更多
疯言疯语
3楼-- · 2019-06-06 11:30

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

查看更多
登录 后发表回答