开发者

is there a way to process .NET/C# variables on external .js?

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 th开发者_如何学编程e .NET myVar value.

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


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>


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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜