There can be a scenario in which you want to call a page method in an aspx.cs file through simple JavaScript.
You can use PageMethods for this.
The following is the procedure.
Let's use the scenario in which you have an image that, on clicking this image you need to update the database and toggle the image in a GridView.
Step 1
Create a web method on aspx.cs page like this:
[WebMethod]
public static string UpdateVisibility(string ID, string Value)
{
UpdateVisibility(int.Parse(ID), bool.Parse(Value));
return string.Empty;
}
Notes
-
You need to add an attribute [WebMethod] to the called function.
-
The Web Method must be static.
Step 2
Create a JavaScript function on the aspx page like this:
function ToggleImage(elem)
{
if (elem.src.indexOf("NotVisible") != -1)
{
elem.src = "../graphics/Visible.gif";
PageMethods.UpdateVisibility(elem.attributes["ID"].value, 'true', onSuccess, onFailure);
}
else
{
elem.src = "../graphics/NotVisible.gif";
PageMethods.UpdateVisibility(elem.attributes["ID"].value, 'false', onSuccess, onFailure);
}
}
function onSuccess(result)
{
}
function onFailure(result)
{
alert(result);
}
Step 3
In aspx.cs in the ItemDataBound method of the GridView, find that image and add attributes to it as in the following:
System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)item.FindControl("ImageID");
//Add attributes of your choice like this
img.Attributes.Add("ID", "ID");
img.Attributes.Add("onclick", "ToggleImage(this);");
That's it, you are done with it.