ASPXページのPostback時にScriptManager .RegisterStartupScript()でjavascriptのfunctionを実行する方法

csharpaspnet

aspxページのボタンを押した時にjavascriptのfunctionを実行したい時は以下の方法が便利です。

まずはASPXページのCSファイルにRegisterStartupScriptを配置します。

以下の例ではindex.aspx.csページにスクリプトを追加してます。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace testapp01
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                ScriptManager.RegisterStartupScript(this, typeof(string), "Error", "loadScript();", true);
            }
        }

    }
}

次はindex.aspxページ内にボタンをクリックしてPostback時にjavascriptアラートメッセージを表示します。


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="testapp01.index" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function loadScript() {
            alert("Hello!");
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

スポンサーリンク

↑ ページの先頭へ

スポンサーリンク