I have a page hierarchy as the following
I want to execute a PageMethod if I click the 'SAVE' button, so I coded like the following
OnClientClick="return btnSaveAS_Clicked()"
private void RegisterJavaScript()
{
StringBuilder jScript = new StringBuilder();
jScript.Append("<script type='text/javascript'>");
jScript.Append(@"function btnSaveAS_Clicked() {
var txtConditionName = document.getElementById('" + txtConditionName.ClientID + @"').value;
PageMethods.Combine('hello','world', OnSuccess);
function onSuccess(result)
{
alert(result);
}
}");
jScript.Append("</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "conditions_key", jScript.ToString());
}
[WebMethod]
public static string Combine(string s1, string s2) {
return s1 + "," + s2;
}
But it gives the following error...
You cannot define page methods in ascx pages. You have to define them in your web form. If you want to have a page method, defined in your user control, you'd have to define a forwarding page method in you aspx page like below (source):
in user control:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string MyUserControlPageMethod()
{
return "Hello from MyUserControlPageMethod";
}
in aspx.cs page:
[WebMethod]
[ScriptMethod]
public static string ForwardingToUserControlMethod()
{
return WebUserControl.MyUserControlMethod();
}
and in aspx page:
function CallUserControlPageMethod()
{
PageMethods.ForwardingToUserControlPageMethod(callbackFunction);
}
Alternatively, you could use ASMX services and jquery
ajax methods (jQuery.ajax, jQuery.get, jQuery.post) to call your methods asynchronously (sample).
Another option would be defining http handlers and call them via jQuery as well (tutorial).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With