views:

8171

answers:

5

Hi all,

I was wondering if anyone can point me in the right direction. I have an asp.net button with an 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

+19  A: 

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

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.

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

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.

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

I learned my WebMethod stuff from: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

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.

Gromer
+1, the ASP related answer is probably the one he is looking for. :)
altCognito
Could be, but I want to believe no one uses classic ASP ;)
Gromer
And I want to spread the good word about using the regex matching for ASP.Net controls!
Gromer
Nah, his tag is asp.net!
Gromer
Do you know how this would work if the button is on a master page?Is there a way to determine the content page name such as ContentPage1.aspx?
zSysop
If the javascript is loaded on every page that uses the master page, it should work fine.
Gromer
+2  A: 

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();
  }
 }
}
Marwan Aouida
Thanks.Is there a way to specify the event if i have more than one button?i.e. btnSave, btnNew and then sever side code behind hasbtnSave_Click, and btnNew_Click events.
zSysop
yes you can, I will update the answer
Marwan Aouida
Thanks I'll try this out.
zSysop
sorry there are some mistakes, I will update the post
Marwan Aouida
+2  A: 

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.

Lucas Richter
why not use the id selector directly like I did in my answer:$('#<%=myButton.ClientID %>')
Marwan Aouida
Good point. I've never run into that with buttons, but your point is very valid.
Gromer
Marwan: No particular reason. It would seem your JQuery-fu is better than mine. Edited.
Lucas Richter
+3  A: 

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.

jacksonakj
This doesn't work for some reason.Here's what i have so far:Code Behindprotected string GetLoginPostBack(){return Page.ClientScript.GetPostBackEventReference(btnLogin,string.Empty);}public void lnkbtnNew_Click(object sender, EventArgs e){ // do stuff }My HTML<script type="text/javascript">$(document).ready(function() {function btnLogin_Click() { <%= GetLoginPostBack() %>;} $("#<%= btnLogin.ClientID %>").click(function() { btnLogin_Click(); });});</script><asp:Button ID="btnLogin" runat="server" Text="Login" />
zSysop
A: 

i m facing error: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

            <asp:GridView ID="gvOrder" runat="server">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Button ID="Button1" runat="server" Text="SendMail" CommandArgument='<%# Eval("OrderID") %>'
                                CommandName="SendMail" />
                            <asp:Button ID="Button2" runat="server" Text="SendAcknowledge" CommandArgument='<%# Eval("OrderID") %>'
                                CommandName="SendAcknowledge" />
                            <asp:Button ID="Button3" runat="server" Text="Cancel" CommandArgument='<%# Eval("OrderID") %>'
                                CommandName="Cancel" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

Protected Sub gvOrder_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvOrder.RowCommand

    If e.CommandName = "SendAcknowledge" Then
        Dim OrderID As Integer = Convert.ToInt32(e.CommandArgument)

        Dim dtOrder As New DataTable()
        objOrder = New Order()
        dtOrder = objOrder.GetOrderByAcknowledge(OrderID)
        Dim body As String
        Dim drCustomer As DataRow = dtOrder.Rows(0)
        Dim CustomerEmail As String = drCustomer("CustomerEmail").ToString()
        Dim CustomerAName As String = drCustomer("CustomerAName").ToString()
        Dim CustomerStreetAddress As String = drCustomer("CustomerStreetAddress").ToString()
        Dim OrderDate As String = drCustomer("OrderDate").ToString()
        Dim OrderDescription As String = drCustomer("OrderDescription").ToString()
        body = ((((((("<html><body>" & "<div >" & "<div>" & "<span>CustomerAName: </span><span>") + CustomerAName & "</span>" & "</div>" & "<div>" & "<span>CustomerStreetAddress: </span><span>") + CustomerStreetAddress & "</span>" & "</div>" & "<div>" & "<span>OrderDate: </span><span>") + OrderDate & "</span>" & "</div>" & "<div>" & "<span>OrderDescription: </span><span>") + OrderDescription & "</span>" & "</div>" & "<div>" & "<span>Company/Organization: *</span><span>") & "</div>" & "</div>" & "</body></html>"))


        objFunction.SendMailMsgWithAttachment("", CustomerEmail, "Order Acknowledgement", body)
pooja