Reputation: 25
I'm using ASP.Net and need to call a server side function after the JavaScript function has completely finished.
The problem is that it's executing the server code before the client code is finished and my hidden value is empty. AJAX call is across domains so using async: false doesn't seem to work.
I've added the basic code below to explain a bit better.
HTML
<input id="hdnToken" type="hidden" name="hdntoken" value="" />
<asp:Button ID="btnSubmit" Text="Submit" OnClientClick="return getToken();" OnClick="btnSubmit_Click" runat="Server"></asp:Button>
JavaScript
function getToken() {
$.ajax({
async: false, // Ignored across domains
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: OnSuccess,
error: OnError
});
function OnSuccess(response) {
$('#hdnToken').val(response);
return true;
}
function OnError(response) {
console.log(response);
return false;
}
};
ASP.Net Server side code
protected void btnSubmit_Click(object sender, EventArgs e)
{
var hidden = Request.Form["hdnToken"];
}
Upvotes: 1
Views: 902
Reputation: 35544
A simple trick would be to place a LinkButton on the page with no text but with an OnClick event.
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"></asp:LinkButton>
Then you can simulate the PostBack from that link with the UniqueID
<script type="text/javascript">
function simulateClick() {
__doPostBack('<%= LinkButton1.UniqueID %>', '');
}
</script>
Now when the simulateClick()
is run, it wil trigger the LinkButton1_Click
method in code behind.
By placing a dummy LinkButton you don't need to disable enableEventValidation
Upvotes: 1