最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - is there a way to process .NETC# variables on external .js? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Sep 6, 2011 at 14:08 markzzzmarkzzz 48.1k126 gold badges319 silver badges534 bronze badges 3
  • I think you can mark the script as .aspx and then you should be able to. – bevacqua 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. – Justin 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 . – Rosmarine Popcorn Commented Sep 6, 2011 at 14:37
Add a ment  | 

3 Answers 3

Reset to default 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>

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 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)

  1. 暂无评论