1

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.

4
  • 3
    Can you change the C-notso-# code that produces this atrocious JavaScript? There isn't really a good reason to use eval. Does C# have a JSON-encoder, or is there a library that does this for you? Commented Aug 12, 2013 at 12:01
  • I am not really using eval. The example suffices in showing the final product. And yes, I can change the code. Do you have any suggestions? Commented Aug 12, 2013 at 12:02
  • How do you pass the string to the web? Commented Aug 12, 2013 at 12:04
  • The javascript gets saved inside of <script> tags inside of an iFrame. The iFrame string gets sent to the front view and the entire frame appended to a predetermined child. Commented Aug 12, 2013 at 12:06

2 Answers 2

1

You can check HttpUtility.JavaScriptStringEncode Method if you are using .net 4 or later framework

Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

I am not using asp.net, but rather winforms.
I don't understand: where's the javascript running? Are you building a web application or a desktop application?
It's not running anywhere. Rather the javascript get created in a desktop application, but then will at a later stage run on a web application.
This sounds like a really weird plan. Anyway, another alternative would be to create a JSON string that you can parse in javascript: "{SomeVar:" + SomeValue + "}";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.