2

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.

mikelt21
  • 2,728
  • 4
  • 23
  • 33

2 Answers2

11

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

fejesjoco
  • 11,763
  • 3
  • 35
  • 65
1

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

Community
  • 1
  • 1
pid
  • 11,472
  • 6
  • 34
  • 63