ASP.NET - how to call server side method using javascript

Asked By abdul rehman on 30-Jun-12 07:20 AM
Ravi Maurya replied to abdul rehman on 30-Jun-12 11:07 AM
To call a server side method on a client side event you need to do the following:

1- Create the server side method:

void DoSomething(...) { ... }

2- Implement the System.Web.UI.IPostBackEventHandler.RaisePostBackEvent which take one string argument (You can assign the name to the value of this argument).:

public void RaisePostBackEvent(string eventArgument)
{
    DoSomething(...);
}

3- Write a script to trigger post back:

function TriggerPostBack(control, arg){
  __doPostBack(control, arg);
}

4- Call the PostBack trigger function when needed:

<a .... onclick="TriggerPostBack('control', 'arg')" .. />
Super Man replied to abdul rehman on 30-Jun-12 01:31 PM
http://stackoverflow.com/questions/3713/call-asp-net-function-from-javascript
abdul rehman replied to abdul rehman on 08-Apr-13 07:07 AM

<asp:TextBox ID="txtName" runat="server" onblur="TriggerPostBack()" ></asp:TextBox>




<script language="javascript" type="text/javascript">



function TriggerPostBack() {



debugger;



var pageId = '<%=Page.ClientID %>';



var txtval = document.getElementById('<%=txtName.ClientID%>');



// __doPostBack(txtval, txtval.value);

__doPostBack(


'__Page', txtval.value )

}

</


script>
.cs





public partial class CallServerMethod : System.Web.UI.Page, IPostBackEventHandler




{




protected override void OnLoad(EventArgs e)

{





// just to know post back event reference wats going on n to get ref name




string postBackEventReference = Page.ClientScript.GetPostBackEventReference(this,string.Empty);




base.OnLoad(e);

}

 

 





public void RaisePostBackEvent(string eventArgument)

{





// u can define method also m(eventArgument)

}
}