简体   繁体   English

在javascript文件.js中访问C#变量

[英]Access C# variable in javascript file .js

Is it possible to create a javascript file with some C# variables? 是否可以使用一些C#变量创建一个javascript文件? 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? 或者我是否必须在usercontrol.ascx中创建它们,我在<head>部分中包含它?

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文件中包含此代码,因为它不是由asp.net编译的,因此不会将CODE_VALUE.foo转换为代码。

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. 你可以做的是在加载你要使用的.js文件之前放置这些变量,并在任何aspx或用户控件上设置它们。

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. 您可以创建一个处理程序来读取javascript文件,包含您的自定义变量并根据需要创建完整的JavaScript代码,并将其作为javascript发送。

Some relative: How to get asp.net client id at external javascript file 一些亲戚: 如何在外部javascript文件中获取asp.net客户端ID

No you cannot use server side tags in .js files. 不,你不能在.js文件中使用服务器端标签。 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. Javascript文件是静态文件,并且静态地由Web服务器提供,而不用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 . 因此,如果您确实要插入该值,则可以创建一个空的.aspx页面并在其中包含所有javascript,然后在script src包含.aspx页面。

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. 但我可能更喜欢使用Web服务,使用web方法,每次需要接收值时都可以通过javascript调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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