Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 334 Vote(s) - 3.51 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Jquery asp.net Button Click Event via ajax

#1
I was wondering if anyone can point me in the right direction.
I have an asp.net button with a click event (that runs some server side code).
What i'd like to do is call this event via ajax and jquery.
Is there any way to do this? If so, i would love some examples.

Thanks in advance
Reply

#2
This is where jQuery really shines for ASP.Net developers. Lets say you have this ASP button:

<asp:Button ID="btnAwesome" runat="server" Text="Hay!" />

When that renders, you can look at the source of the page and the id on it won't be btnAwesome, but $ctr001_btnAwesome or something like that. This makes it a pain in the butt to find in javascript. Enter jQuery.

<pre>
$(document).ready(function() {
$("input[id$='btnAwesome']").click(function() {
// Do client side button click stuff here.
});
});
</pre>

The id$= is doing a regex match for an id ENDING with btnAwesome.

Edit:

Did you want the ajax call being called from the button click event on the client side? What did you want to call? There are a lot of really good articles on using jQuery to make ajax calls to ASP.Net code behind methods.

The gist of it is you create a **static** method marked with the WebMethod attribute. You then can make a call to it using jQuery by using $.ajax.

<pre>
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
</pre>

I learned my WebMethod stuff from: [

[To see links please register here]

][1]

A lot of really good ASP.Net/jQuery stuff there. Make sure you read up about why you have to use msg.d in the return on .Net 3.5 (maybe since 3.0) stuff.


[1]:

[To see links please register here]

Reply

#3
ASP.NET web forms page already have a JavaScript method for handling PostBacks called "__doPostBack".

function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}

Use the following in your code file to generate the JavaScript that performs the PostBack. Using this method will ensure that the proper ClientID for the control is used.

protected string GetLoginPostBack()
{
return Page.ClientScript.GetPostBackEventReference(btnLogin, string.Empty);
}

Then in the ASPX page add a javascript block.

<script language="javascript">
function btnLogin_Click() {
<%= GetLoginPostBack() %>;
}
</script>

The final javascript will be rendered like this.

<script language="javascript">
function btnLogin_Click() {
__doPostBack('btnLogin','');
}
</script>

Now you can use "btnLogin_Click()" from your javascript to submit the button click to the server.
Reply

#4
In the client side handle the click event of the button, use the ClientID property to get he id of the button:

$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(

function() {
$.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
// do something with the data
return false;
}
});
});

In your page on the server:

protected void Page_Load(object sender,EventArgs e) {
// check if it is an ajax request
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
if (Request.QueryString["id"]==myButton.ClientID) {
// call the click event handler of the myButton here
Response.End();
}
if (Request.QueryString["id"]==mySecondButton.ClientID) {
// call the click event handler of the mySecondButton here
Response.End();
}
}
}
Reply

#5
I like Gromer's answer, but it leaves me with a question: What if I have multiple 'btnAwesome's in different controls?

To cater for that possibility, I would do the following:

$(document).ready(function() {
$('#<%=myButton.ClientID %>').click(function() {
// Do client side button click stuff here.
});
});

It's not a regex match, but in my opinion, a regex match isn't what's needed here. If you're referencing a particular button, you want a precise text match such as this.

If, however, you want to do the same action for every btnAwesome, then go with Gromer's answer.
Reply

#6
I found myself wanting to do this and I reviewed the above answers and did a hybrid approach of them. It got a little tricky, but here is what I did:

My button already worked with a server side post. I wanted to let that to continue to work so I left the "OnClick" the same, but added a OnClientClick:

OnClientClick="if (!OnClick_Submit()) return false;"

Here is my full button element in case it matters:

<asp:Button UseSubmitBehavior="false" runat="server" Class="ms-ButtonHeightWidth jiveSiteSettingsSubmit" OnClientClick="if (!OnClick_Submit()) return false;" OnClick="BtnSave_Click" Text="<%$Resources:wss,multipages_okbutton_text%>" id="BtnOK" accesskey="<%$Resources:wss,okbutton_accesskey%>" Enabled="true"/>

If I inspect the onclick attribute of the HTML button at runtime it actually looks like this:

if (!OnClick_Submit()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$ctl03$RptControls$BtnOK", "", true, "", "", false, true))

Then in my Javascript I added the OnClick_Submit method. In my case I needed to do a check to see if I needed to show a dialog to the user. If I show the dialog I return false causing the event to stop processing. If I don't show the dialog I return true causing the event to continue processing and my postback logic to run as it used to.

function OnClick_Submit() {
var initiallyActive = initialState.socialized && initialState.activityEnabled;
var socialized = IsSocialized();
var enabled = ActivityStreamsEnabled();

var displayDialog;

// Omitted the setting of displayDialog for clarity

if (displayDialog) {
$("#myDialog").dialog('open');
return false;
}
else {
return true;
}
}

Then in my Javascript code that runs when the dialog is accepted, I do the following depending on how the user interacted with the dialog:

$("#myDialog").dialog('close');
__doPostBack('message', '');


The "message" above is actually different based on what message I want to send.

But wait, there's more!
-----------------------

Back in my server-side code, I changed OnLoad from:

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
return;
}

// OnLoad logic removed for clarity
}

To:

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
switch (Request.Form["__EVENTTARGET"])
{
case "message1":
// We did a __doPostBack with the "message1" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message1", null));
break;

case "message2":
// We did a __doPostBack with the "message2" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message2", null));
break;
}
return;
}

// OnLoad logic removed for clarity
}

Then in BtnSave_Click method I do the following:

CommandEventArgs commandEventArgs = e as CommandEventArgs;
string message = (commandEventArgs == null) ? null : commandEventArgs.CommandName;

And finally I can provide logic based on whether or not I have a message and based on the value of that message.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through