2017年6月14日 星期三

ASP.NET input button使用javascript觸發postback

不使用ASP.NET WebForm Button控制項,使用html Button並在Button的onclick事件中,使用javascript觸發postback,在Page_Load中去確認哪一個按鈕觸發。

以下的作法,不曉得是否正確,還請各位程式設計師們不吝指教。

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript">
        function Button1_Click() {
            <%=ClientScript.GetPostBackEventReference(Me, "Button1_Click").ToString%>
        };
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="Button1" type="button" value="測試javascript觸發postback" onclick="Button1_Click();" />
        <span id="span_message" runat="server">[訊息顯示在此處]</span>
    </div>
    </form>
</body>
</html>


test_js_postback.aspx.vb
Partial Class test_js_postback
    Inherits System.Web.UI.Page

    Private Sub test_js_postback_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
        Else
            Dim con As Control = Nothing
            Dim str_event_target As String = String.Empty
            Dim str_event_targument As String = String.Empty
            str_event_target = Page.Request.Params.Get("__EVENTTARGET") 'html hidden __EVENTTARGET
            str_event_targument = Page.Request.Params.Get("__EVENTARGUMENT") 'html hidden __EVENTARGUMENT

            If (Not str_event_target Is Nothing) And (str_event_target <> "") Then
                con = Page.FindControl(str_event_target)
                Response.Write("EVENTTARGET=[" & str_event_target & "][" & con.GetType.ToString & "]<br/>")
                If InStr(1, str_event_target.ToLower, "page", CompareMethod.Text) > 0 Then
                    If (Not str_event_targument Is Nothing) And (str_event_targument <> "") Then
                        Response.Write("EVENTARGUMENT=[" & str_event_targument & "]<br/>")
                        If str_event_targument = "Button1_Click" Then 'html input的Button1_Click
                            Me.span_message.InnerHtml = "觸發Button1_Click<br/>"
                        End If
                    Else
                        Response.Write("EVENTARGUMENT=[無]<br/>")
                    End If
                End If

            Else
                Response.Write("PostBack:可能是某個控制項送出<br/>")
            End If

        End If
    End Sub
End Class

沒有留言:

張貼留言