Asp.net在类库中编译js作为嵌入资源,其中包含c#代码

Asp.net compile js in class library as embedded resource with c# code inside

本文关键字:嵌入资源 包含 代码 net 类库 编译 js Asp      更新时间:2023-09-26

在我的类库中,我嵌入了一些js和css文件,以便在我的asp.net应用程序中使用,如这里所描述的方法。现在我要把一些c#代码在js文件中,并让它在生成的dll中编译。有可能吗?

例子:somefile.js

function foo() 
{
    var a = "<%= SOME_CONSTANT_DECLARED_OUTSIDE %>";
    <% ... some conditional code %>
}

Javascript是客户端,c#是服务器端。

你不能在Javascript中运行c#

. NET不编译,也不查找*.js文件中的托管代码(编译的代码,如c#代码)。所以当你把一些c#代码在js文件中,代码将不工作作为c#代码(客户端将尝试使用它作为javascript代码)。

但是有一个变通方法——ASP。. NET 使在aspx文件中呈现c#代码。所以你可以在JS函数中嵌入一些c#代码,只要这个函数位于aspx文件中(在脚本标签中)。

文档告诉你如何添加一个变量。-

在UpdatePanelAnimation.js中你有这几行代码

BorderAnimation = function(color) {
    this._color = color;
}

然后自动设置。

Dim script As String = String.Format( _
               CultureInfo.InvariantCulture, _
               "Sys.Application.add_load(function(sender, args) {{var {0}_borderAnimation = new BorderAnimation('{1}');var panelElement = document.getElementById('{0}');if (args.get_isPartialLoad()) {{{0}_borderAnimation.animate(panelElement);}}}});", _
               updatePanel.ClientID, _
               ColorTranslator.ToHtml(BorderColor))

        ScriptManager.RegisterStartupScript( _
            Me, _
            GetType(UpdatePanelAnimationWithClientResource), _
            ClientID, _
            script, _
            True)

因此格式化的{1}被替换为您在服务器端拥有的BorderColor。现在你可能想要像这样更新JS构造函数

BorderAnimation = function(color, otherValue) {这一点。_color = color;这一点。_otherValue = otherValue}

对服务器端格式也做同样的处理但是你要做

...
var {0}_borderAnimation = new BorderAnimation('{1}', '{2}')
...

这是如何ASP。. NET将后端与前端"连接"起来。有一些其他的方法(更优雅)来做到这一点,但这不是问题的关键。