Search code examples
c#jqueryasp.netfunctionwebmethod

How to use ScriptManager.RegisterStartupScript in a WebMethod in asp.net?


I have a condition where i need to call a jquery function using a webmethod as below:

[WebMethod]
public static void BindData(String Site)
{
    String HTML = "";
    Int32 i = 1;
    DataTable dt = new DataTable();
    dt = obj.GetAll(objprop);
    if (dt.Rows[0]["UserId"].ToString() != "0")
    {
        foreach (DataRow item in dt.Rows)
        {
            string Email = Bal.Common.Decryptdata(item["Email"].ToString());
            string SentInvitation = item["SentInvitation"].ToString();

            SentInvitation = SentInvitation.ToString() == "1" ? "Already Invited" : "";
            if (i % 2 == 0)
                HTML += "<div class=~other_wish_row2~><div class=~friend_list_box1~><input type=~checkbox~ class=~chkEmail~ id=~chkId^" + i + "~/></div><div class=~friend_list_box2~><p><label id=~lbl" + i + "~>" + Email.ToString() + "</label><label class=~SentInvitationLbl~ id=~lblSentInvitation" + i + "~>" + SentInvitation + "</label></p></div><div class=~friend_list_box3~></div><div class=~clear~></div></div>";
            else
                HTML += "<div class=~other_wish_row3~><div class=~friend_list_box1~><input type=~checkbox~ class=~chkEmail~ id=~chkId^" + i + "~/></div><div class=~friend_list_box2~><p><label id=~lbl" + i + "~>" + Email.ToString() + "</label><label class=~SentInvitationLbl~ id=~lblSentInvitation" + i + "~>" + SentInvitation + "</label></p></div><div class=~friend_list_box3~></div><div class=~clear~></div></div>";

            i = i + 1;
        }
        ScriptManager.RegisterStartupScript((Page)(HttpContext.Current.Handler), typeof(Page), "hdrEmpty1", "Test('" + HTML + "');", true); return;
    }
    else
    {

    }
}

Jquery Code is:

function Test(data) {
   alert('hi');
}

function Binddata(SocialSite) {

$.ajax({
    type: "POST",
    url: "InviteFriends.aspx/BindData",
    data: "{SocialSite:'" + SocialSite + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {

    }
 });
}

I am not able to fire Test(), please help to resolve this.


Solution

  • You can't do this from a web service (either an .asmx file or a WebMethod) as it does not run in the context of a normal page. I see you're using AJAX, you'll have to do the handling in the success callback method of your jQuery.ajax() call, like so:

     function Test(data) {
        alert('hi');
     }
    
     function Binddata(SocialSite) {
    
     $.ajax({
         type: "POST",
         url: "InviteFriends.aspx/BindData",
         data: "{SocialSite:'" + SocialSite + "'}",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (data) {
             Test(data);
         }
      });
     }