将javascript导入c#类

时间:2013-06-27 15:13:17

标签: c# javascript

我在C#(Class1.cs)中创建了一个使用javascript执行某些命令(JavaScript1.js)的类。 我知道如果我将这个javascript导入到WebForm1.ASPX(使用Class1.cs的那个)中,它就会起作用。 问题是我希望能够在其他WebForms中使用这个Class1.cs类。为此,我必须将此javascript导入到每个WebForm中。 有没有办法将它导入课堂?

以下是一个例子:

主页

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<%@ Import Namespace="WebApplication1"%>

<script runat="server">
    protected void Test(object sender, EventArgs e)
    {
        Class1 class1 = new Class1();
        class1.callSomething();
    }
</script>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="JavaScript1.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" OnClick="Test" Text ="ALERT"/>
    </div>
    </form>
</body>
</html>

CLASS

using System;

namespace WebApplication1
{
    public class Class1
    {
        public void callSomething()
        {
            // Here I call the javascript.
        }
    }
}

JAVASCRIPT

function alertTest()
{
    alert('worked');
}

在这种情况下我使用:

<script src="JavaScript1.js" type="text/javascript"></script>

但是这样,我必须把它放在每一个webform中。我想要做的是在课堂上导入(Class1)。

提前致谢。

1 个答案:

答案 0 :(得分:1)

ClientScriptManager.RegisterClientScriptBlock方法会help你。

如果您正在进行自定义控制并希望自动加载.js文件,则可以将其作为资源添加到项目中:

 public class FancyGridView : GridView
    {

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.Page.ClientScript.RegisterClientScriptResource(
                typeof(FancyGridView), "FancyCustomControls.Scripts.GridViewScript.js");
        }
...
}
需要将

GridViewScript.js添加为资源(在其选项\构建操作中设置“嵌入资源”)并将其添加到AssemblyInfo

[assembly: WebResource("FancyCustomControls.Scripts.GridViewScript.js", "text/javascript")]