简体   繁体   中英

Javascript string in C# escaping issue

I am having a problem with javascript.

The javascript gets created dynamically on a C# winforms project as a string.

The actual javascript code gets generated fine and all the double quotes get escaped as they should. My problem comes in when I assign a string inside of this function such as

string js = "eval(\"var someVar = 'someValue'\");";

So I end up with a string in the browser as

eval(\"var someVar = 'someValue'\");

The problem is the "\\" that is escaping the " in front of 'someVar'. It gets put in automatically in C#. That makes the string invalid when trying to execute the actual function in a browser. Any ideas how I might go about solving this?

Thanks.

如果使用的是.net 4或更高版本的框架,则可以检查HttpUtility.JavaScriptStringEncode方法。

You shouldn't need eval. This is how I do what you're trying to do.

Step 1: set up a Literal object on your aspx page. I put the literal in a hidden div.

<div style="display:none;" id="TheDiv">
   <asp:Literal runat="server" ID="TheLiteral" />
</div>

Step 2: inject the value in the literal into the C# code behind file.

TheLiteral.Text = SomeValue;
TheLiteral.Text = SomeValue.ToString(); // in case SomeValue is not a string

Step 3: get the value from the client:

var SomeVar = $('#TheDiv').text();
$('#TheDiv').remove();

For sure, there are other ways of doing it as well but this method works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM