开发者

How to deal with double quotes in JavaScript when referencing a C# variable

开发者 https://www.devze.com 2023-03-15 02:22 出处:网络
I\'m needing to call a JavaScript function that takes in a string variable that could have double quotes in it.Here\'s how I pass my variable into the JavaScript function:

I'm needing to call a JavaScript function that takes in a string variable that could have double quotes in it. Here's how I pass my variable into the JavaScript function:

onclick="copyDescription('<%# Eval("Description") %>');"

The problem is the function never fires because it doesn't like the quotes that might be in the 'Description' variable.

'Description', for example, could be:

VALVE BALL 1" 2000 RP THRD NACE SS BALON LS-10561

If I remove the double quote from the above description, it wor开发者_运维百科ks great. I further tested this out by doing the following, and it worked as expected:

        $(document).ready(function () {
        var str = 'VALVE BALL 1" 2000 RP THRD NACE SS BALON LS-10561';
        copyDescription(str);
    });

I tried doing a .replace('"','\"') and a .replace('"','') via JavaScript, but neither worked. I can remove the quotes by modifying the C# code that gets the value to remove the double quote, and it works. Just not through JavaScript. Any ideas?


The problem is that the " is terminating the HTML attribute and cutting off the JS mid-statement.

Double quotes must be represented as &quot; in attribute values delimited by double quotes.


Use the Microsoft Anti-Cross Site Scripting Library and call function JavaScriptEncode() on your string


The solution I went with which was the answer to my question was to use:

onclick="copyDescription('<%# Server.HtmlEncode(Eval("Description").ToString()) %>');"

Server.HtmlEncode works how I need it to.

Thanks everyone for your help and answers!


Have that Eval call output JSON instead or plaintext. That'll take care of any embedded Javascript metacharacters. I don't know how that'd be done in C#, but in PHP it's simply:

 onclick="copyDescription(<?php echo json_encode(...) ?>);"
0

精彩评论

暂无评论...
验证码 换一张
取 消