How to call code behind server method from a client side JavaScript function?
Solution 1:
Yes, you can make a web method like..
[WebMethod]
public static String SetName(string name)
{
return "Your String"
}
And then call it in JavaScript like,
PageMethods.SetName(parameterValueIfAny, onSuccessMethod,onFailMethod);
This is also required :
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Solution 2:
In my projects, we usually call server side method like this:
in JavaScript:
document.getElementById("UploadButton").click();
Server side control:
<asp:Button runat="server" ID="UploadButton" Text="" style="display:none;" OnClick="UploadButton_Click" />
C#:
protected void Upload_Click(object sender, EventArgs e)
{
}
Solution 3:
If you dont want to use ajax than
Code behind
void myBtn_Click(Object sender,EventArgs e)
{
//SetName(name); your code
}
.aspx file
<script language="javascript" type="text/javascript">
function btnAccept_onclick() {
var name;
name = document.getElementById('txtName').value;
document.getElementById('callserver').click();
// Call Server side method SetName() by passing this parameter 'name'
</script>
<div style="dispaly:none;">
<input type="button" id="callserver" value="Accept" click="myBtn_Click" runat="server" />
</div>
<input type="button" id="btnAccept" value="Accept" onclick="return btnAccept_onclick()" />
or use page method
.cs file
[ScriptMethod, WebMethod]
public static string docall()
{
return "Hello";
}
.aspx file
<script type="text/javascript">
function btnAccept_onclic() {
PageMethods.docall(onSuccess, onFailure);
}
function onSuccess(result) {
alert(result);
}
function onFailure(error) {
alert(error);
}
</script>
check this : http://blogs.microsoft.co.il/blogs/gilf/archive/2008/10/04/asp-net-ajax-pagemethods.aspx