Reputation: 221
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.
Upvotes: 1
Views: 328
Reputation: 51917
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.
Upvotes: 1
Reputation: 1156
You can check HttpUtility.JavaScriptStringEncode Method if you are using .net 4 or later framework
Upvotes: 1