-1

JavaScript を使用していくつかのコマンド (JavaScript1.js) を実行するクラスを C# (Class1.cs) で作成しました。この JavaScript を WebForm1.ASPX (Class1.cs を使用するもの) にインポートすると、動作することがわかっています。問題は、この Class1.cs クラスを他の WebForms で使用できるようにしたいということです。そのためには、この JavaScript をすべての Web フォームにインポートする必要があります。クラスにインポートする方法はありますか?

次に例を示します。

メインページ

<%@ 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>

クラス

using System;

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

ジャバスクリプト

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

この場合、私は使用しています:

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

しかし、この方法では、これをすべての Web フォームに配置する必要があります。私がしたいのは、クラス(Class1)でのインポートです。

前もって感謝します。

4

1 に答える 1

1

ClientScriptManager.RegisterClientScriptBlockメソッドが役立ちます。

カスタム コントロールを作成していて、.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")]
于 2013-06-27T15:15:13.003 に答える