在javascript文件.js中访问C#变量 [英] Access C# variable in javascript file .js
问题描述
是否可以使用一些C#变量创建一个javascript文件?这样的事情:
Is it possible to create a javascript file with some C# variables? Something like this:
var foo = <%= CODE_VALUE.foo %>;
或者我必须在usercontrol.ascx中创建它们,我包含在<$ c $中c>< head> 部分?
Or do I have to create them in a usercontrol.ascx which I include in the <head>
section?
推荐答案
您不能在.js中包含此代码文件因为不是由asp.net编译的,所以不会将 CODE_VALUE.foo
翻译成代码。
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.
什么你可以做的就是在加载你想要使用的.js文件之前放置这些变量,并在任何aspx或用户控件上设置它们。
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.
例如
<script>
var foo = <%=CODE_VALUE.foo%>;
<script>
<script type="text/javascript" src="fileToUseTheFoo.js">
</script>
另外你可以创建一个读取javascript文件的处理程序,包含你的自定义变量并创建一个完整的javascript代码如你所愿,并将其作为javascript发送。
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.
一些亲戚:如何在外部javascript文件中获取asp.net客户端ID
这篇关于在javascript文件.js中访问C#变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!