Avoid quoting a variable in MVC View to pass as a Javascript parameter

I have an MVC view in which I need to pass a string variable to javascript, but this string variable has single quotes in it ( ' ). I'm trying to do something like this

 <a onclick="JavaScript:AddressHandler.ProcessAddress('<%= homeAddress %>');" class="button-link">change</a> 

homeAddress has single quotes, which I have to somehow workaround so that I can pass its value to javascript. Any help in this regard is greatly appreciated.

+4
source share
5 answers

To avoid a string being a Javascript string literal, you replace the backslash with double backslashes and a backslash and delimiter string separator:

 <a onclick="AddressHandler.ProcessAddress('<%= homeAddress.Replace(@"\", @"\\").Replace("'", @"\'") %>');" class="button-link">change</a> 

Note. javascript: protocol javascript: used when you put a script in a url and not as an event handler.

Edit:
If the script also contains characters that require HTML encoding, this should be done after escaping the Javascript string:

 <a onclick="<%= Html.Encode("AddressHandler.ProcessAddress('" + homeAddress.Replace(@"\", @"\\").Replace("'", @"\'") +"');") %>" class="button-link">change</a> 

So, if you don’t know what the string contains in order to be safe, you need to first avoid the string literal and then HTML code the code so that it can be placed in the attribute of the HTML tag.

+4
source

You can use the Ajax helper: Ajax.JavaScriptStringEncode(string strToEncode)

+12
source

You can write a method that avoids all single quotes (and other characters, if necessary) with a backslash, so javascript does not understand it.

0
source

You want to encode homeAddress as a url. To do this, MVC has a built-in helper: UrlHelper.Encode (string url) - it must replace one quote %27

0
source

I don’t have time to check it out, but look at HtmlHelper.Encode (line s). He can handle the escape for you.

-one
source

All Articles