简体   繁体   中英

Access C# variable in javascript file .js

Is it possible to create a javascript file with some C# variables? Something like this:

var foo =  <%= CODE_VALUE.foo %>;

Or do I have to create them in a usercontrol.ascx which I include in the <head> section?

You can not have this code inside the .js file because is not compile by asp.net and so is not translate the CODE_VALUE.foo into code.

what you can do is to place this variables just before load this .js file that you won to use, and set them on any aspx or user control.

For example

<script>
 var foo = <%=CODE_VALUE.foo%>;
<script>
<script type="text/javascript" src="fileToUseTheFoo.js">   
</script>

alternative you can create a handler that read javascript files, include your custom variables and create a full javascript code as you like, and send it as javascript one.

Some relative: How to get asp.net client id at external javascript file

No you cannot use server side tags in .js files. Instead create the variables on the pages/controls where you need them.

Javascript files are static files, and served by the web server statically as well, without processing them with ASP.NET.

So if you really want to insert that value, you can create an empty .aspx page and include all the javascript in there, and then include the .aspx page in script src .

But I would probably prefer to have a web service instead, with a web method which you would call from javascript every time you need to receive the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM