How to call server function using JavaScript, or How to trigger button's click event by using JavaScript. For example: You have a linkbutton in your page, and the linkbutton's click event will do something.
<asp:LinkButton ID="lbtnGetDetails" runat="server" style="display:'none';" OnClick="lbtnGetDetails_Clicked" />
protected void lbtnGetDetails_Clicked(object sender, EventArgs e)
{
LoadDetails();
}
There are serval way you can do this:
1. The simplest way:
function getDetails() {
__doPostBack('<%= lbtnGetDetails.UniqueID %>', '');
}
2. If you have script manager in your page, you can use:
function __ButtonClick(bid){
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm._doPostBack(bid, '');
}
__ButtonClick('<%= lbtnGetDetails.UniqueID %>', '');
But there is a bug in these 2 solutions. They can not trigger the client validation function. They will skip the validation function. After some search in google, here is my final solution:
3. Final solution:
PostBackOptions pbo = new PostBackOptions(lbtnGetDetails);
pbo.PerformValidation = lbtnGetDetails.CauseValidation;
pbo.ValidationGroup = lbtnGetDetails.ValidationGroup;
string js = ClientScript.GetPostBackEventReference(pbo);
"js" is the function you need to call in your javascript.
Example for 3:
in your aspx you have a function TriggerButtonClick(');
function TrigerButtonClick()
{
<%=ButtonClickJs %>
}
In you aspx.cs you have a property:
protected string ButtonClickJs
{
get
{
PostBackOptions pbo = new PostBackOptions(lbtnGetDetails);
pbo.PerformValidation = lbtnGetDetails.CauseValidation;
pbo.ValidationGroup = lbtnGetDetails.ValidationGroup;
return ClientScript.GetPostBackEventReference(pbo);
}
}
So if you call "TrigerButtonClick()" using JavaScription. It will trigger the button click event, and do the validations before postback.