ASP.NET asynchronous post-back on asp:button click

人走茶凉 提交于 2019-12-02 02:03:14

问题


I am using AJAX in asp:net and am trying to handle a situation where an asp:button triggers both a javascript method and a codebehind c# method. To do this I am using onclick and onClientClick attributes for the button. I need a postback to occur for the codebehind to be called however this postback causes the javascript to not work because variables have lost state. Can anyone describe how to handle this? Possible with ajax and async postbacks? It's starting to drive me a bit crazy!

Edit: The javascript is actually for a google-map (v3), the c# code is for submitting to an sql db.

The map is initialized in the code-behind with:

protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack) {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "onload", "initialize_map();", true);
            submitButton.Command += new CommandEventHandler(this.submitButton_Click);
        }
    }

Here is some of the relevant code:

<asp:UpdatePanel runat="server" ID="Form" UpdateMode="Conditional">
<ContentTemplate>

(...form stuff...)

<asp:Button ID="submitButton" runat="server" Text="Submit" ValidationGroup="NewCallFormSubmit" OnClientClick="calcRoute(); return false;" onclick="submitButton_Click" />

</ContentTemplate>
</UpdatePanel>

<asp:UpdatePanel runat="server" ID="DisplayUpdatePanel" UpdateMode="Conditional">
<ContentTemplate>

 <h1>
  Pick-Up and Drop-Off Locations
  </h1>
     <!-- Map Layout -->
     <div id="map_canvas" style="width: 500px; height: 500px;"></div>                          

</ContentTemplate>
</asp:UpdatePanel>

...I think it would work if I could get the first updatepanel to postback on the button click, the second panel not to postback, and the button to still call the codebehind. So far no luck with this all happening at the same time.


回答1:


If you simply want to run your OnClientClick (client) code before your OnClick (server) code, try the following:

ASP.NET

<asp:Button ID="btn_mybutton" runat="server" Text="MyButton" OnClientClick="return JSFunction();" OnClick="CFunction"/>

Javascript

<script type="text/javascript">
    function JSFunction() {
        alert('Some JavaScript stuff');
        return true; 
    }
</script>

C#

protected void CFunction(object sender, EventArgs e)
{
    // Some server code
}

The JavaScript function is executed first and returned from before the server code is executed.



来源:https://stackoverflow.com/questions/8874697/asp-net-asynchronous-post-back-on-aspbutton-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!