问题
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