ASP.NET JavaScriptからAjaxのUpdatePanelを更新する

ボタンをクリックして検索画面等のポップアップ画面を起動し、
その画面で選択した値をテキストボックスに表示した後、
テキストボックスのTextChangedイベントを発生させたい事ってありますよね。

UpdatePanelの更新トリガーとなるようボタンコントロールを配置します。
ボタンのスタイルで可視性を非表示に設定します。


そしてポップアップ画面で選択した値を、テキストボックスに表示するJavaScriptの最後に、
以下のコードを追加します。
document.getElementById('UpdatePanelの更新トリガーボタンコントロールのクライアントID').click();

Default.aspx
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

        <asp:ScriptManager ID="ScriptManager1" runat="server" />

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">

            <ContentTemplate>

                <asp:TextBox ID="txtCode" runat="server" Width="100px"></asp:TextBox>&nbsp;<asp:Button
                    ID="btnSearch" runat="server" Text="検索" />

                &nbsp;<asp:TextBox ID="txtName" runat="server" BorderStyle="None"></asp:TextBox>

                &nbsp;<br />

                <br />

                <asp:Label ID="lblOther" runat="server"></asp:Label>&nbsp;




                <asp:Button ID="btnTrigger" runat="server" Style="visibility: hidden" Text="Button" />




            </ContentTemplate>

        </asp:UpdatePanel>

    </form>

</body>

</html>




Partial Class _Default

    Inherits System.Web.UI.Page



    Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgs) _

    Handles Me.Load

        If Not IsPostBack Then

            Call OutputJavaScript()




            Me.btnSearch.Attributes("onclick") = "javascript:OpenPopup();"




            'ReadOnly=Trueに設定されたテキストボックスにJavaScriptから設定した値が

            'PostBack時に値が消去されてしまうバグの回避

            'http://support.microsoft.com/kb/917733/ja

            'デザイナではReadOnly=FalseにしておきJavaScriptよりReadOnlyを設定する。

            Me.txtName.Attributes.Add("readOnly""readOnly")

        End If

    End Sub




    Protected Sub txtCode_TextChanged(ByVal sender As ObjectByVal e As System.EventArgs) _

    Handles txtCode.TextChanged

        Me.lblOther.Text = CInt(Me.txtCode.Text).ToString("D5") & ":" & Me.txtName.Text & "  ~Set From TextChanged~"

    End Sub




    Private Sub OutputJavaScript()

        Dim str As New System.Text.StringBuilder

        With str

            .Append(vbCrLf & "  window.onunload = subWin_UnLoad;")

            .Append(vbCrLf & "  subWin = new Array();")




            .Append(vbCrLf & "  function subWin_UnLoad(){")

            .Append(vbCrLf & "      for (field in subWin) {")

            .Append(vbCrLf & "          if (subWin[field].closed) {")

            .Append(vbCrLf & "              continue;")

            .Append(vbCrLf & "          }")

            .Append(vbCrLf & "          subWin[field].close();")

            .Append(vbCrLf & "      }")

            .Append(vbCrLf & "  }")




            .Append(vbCrLf & "  function OpenPopup(){")

            .Append(vbCrLf & "      javascript:subWin[0] = window.open('Popup.aspx','Popup','menubar=no,toolbar=no,location=no,directories=no,status=yes,scrollbars=yes,resizable=yes,width=500,height=500,top=100,left= 50');")

            .Append(vbCrLf & "      subWin[" & 0 & "].focus();")

            .Append(vbCrLf & "  }")




            .Append(vbCrLf & "  function SetPopupResult(cd,name){")

            .Append(vbCrLf & "      document.getElementById('" & Me.txtCode.ClientID & "').value = cd;")

            .Append(vbCrLf & "      document.getElementById('" & Me.txtName.ClientID & "').value = name;")





            '--UpdatePanelを更新させるために、UpdatePanel更新トリガーのボタンクリックを行う

            .Append(vbCrLf & "      document.getElementById('" & Me.btnTrigger.ClientID & "').click();")





            .Append(vbCrLf & "  }")

        End With

        ClientScript.RegisterStartupScript(Me.GetType(), "JavaScript", str.ToString, True)





    End Sub




    

End Class



Popup.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Popup.aspx.vb" Inherits="Popup" %>



<!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>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        &nbsp;<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">

            <Columns>

                <asp:ButtonField Text="選択" />

                <asp:BoundField DataField="CD" HeaderText="コード">

                    <HeaderStyle Width="100px" />

                </asp:BoundField>

                <asp:BoundField DataField="Name" HeaderText="名称">

                    <HeaderStyle Width="100px" />

                </asp:BoundField>

            </Columns>

        </asp:GridView>

    

    </div>

    </form>

</body>

</html>


Imports System.Data




Partial Class Popup

    Inherits System.Web.UI.Page




    Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgs) _

    Handles Me.Load

        Call OutputJavaScript()

        Me.GridView1.DataSource = CreateData()

        Me.GridView1.DataBind()

    End Sub




    Protected Sub GridView1_RowDataBound(ByVal sender As ObjectByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _

    Handles GridView1.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim rowData As DataRowView = DirectCast(e.Row.DataItem, DataRowView)

            e.Row.Cells(0).Attributes.Add("OnClick"String.Format("javascript:ReturnSelect('{0}','{1}');", rowData("CD").ToString, rowData("NAME").ToString))

        End If

    End Sub




    Private Function CreateData() As DataTable

        Dim dt As New DataTable

        dt.Columns.Add(New DataColumn("CD"GetType(Integer)))

        dt.Columns.Add(New DataColumn("NAME"GetType(String)))




        For i As Integer = 1 To 10

            dt.Rows.Add(New Object() {i, "Name" & i.ToString})

        Next

        Return dt

    End Function




    Private Sub OutputJavaScript()

        Dim str As New System.Text.StringBuilder

        With str

            .Append(vbCrLf & "function ReturnSelect(cd,name){")

            .Append(vbCrLf & "  window.opener.SetPopupResult(cd,name);")

            .Append(vbCrLf & "  window.close();")

            .Append(vbCrLf & "}")

        End With

        ClientScript.RegisterStartupScript(Me.GetType"JavaScript", str.ToString, True)


    End Sub

End Class

0 件のコメント: