3

I have my variable in an aspx.cs , such as :

protected string myVar="Hello";

Now, if I go to my scripts.js file added as :

<head>
    <script src="/scripts/scripts.js" type="text/javascript"></script>
</head>

and I try this :

var myVarJs="<%=myVar&>";

it doesnt get the .NET myVar value.

Is there a way to catch it or am I dreaming?

3
  • I think you can mark the script as .aspx and then you should be able to. Commented Sep 6, 2011 at 14:17
  • There are ways that you can get ASP.Net to dynamically process .js files, however doing this sort of thing inside a .js file is a bad idea as it would probably break client side caching. The answer that Ivan has posted is a much better solution. Commented Sep 6, 2011 at 14:20
  • I would like to see which is the best way to pass an Array to java script array ,maybe 2 dimensional String Array's . Commented Sep 6, 2011 at 14:37

3 Answers 3

7

Insert the variable before the script:

<head>
    <script type="text/javascript"> var myVarJs="<%=myVar%>"; </script>
    <script src="/scripts/scripts.js" type="text/javascript"></script>
</head>
Sign up to request clarification or add additional context in comments.

Comments

2

You can also register/render client script. So you can declare variables in the backend and then render the javascript variables.

1 Comment

Check this ClientScriptManager out msdn.microsoft.com/en-us/library/…
2

I don't think it is possible to directly access C# variable in javascript code. As C# is client side and Javscript is server side.

Unless on the Asp.net page you save the variable in a hidden field or label as text which is not visible.

Asp:

<asp:HiddenField ID="hidden" runat="server" value="<%=strvariable %>" />

Javascript:

function Button_Click()
{
    alert(document.getElementById('hidden').value); 
}

So this would get the hidden field with the ID of "hidden".

This could work I think.

Comments

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.