How can I call a function in a UserControl (code behind - UserControl.ascx.cs) using javascript? The following doesn't seem to work. It only works if I move the function (AddLike) to the code behind of the parent page that nests the UserControl. If the function to be called is in the code behind of the UserControl itself, it doesn't work
UserControl.ascx
$.ajax({
type: "POST",
url: "UserControl.ascx.cs/AddLike", //This doesn't seem to work
data: "{ IDphoto :" + IDphoto + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
})
UserControl.ascx.cs
[WebMethod]
public static string AddLike(int IDphoto)
{
//My code
}
parentPage.aspx
<uc:UserControl runat="server" />
You cannot call WebMethods
from usercontrol. Put this WebMethod
in code behind of page in which your control will be loaded. Change it like this
$.ajax({
type: "POST",
url: "parentPage.aspx/AddLike",
data: "{ IDphoto :" + IDphoto + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
})
You cannot call a WebMethod
defined in code behind of user control. So what you can do to avoid repetitive code is define your method as a static
one in code behind of user control like this:-
public static string AddLike(int IDphoto)
{
//My code
}
And then call this method from your respective aspx
page, which obviously you will trigger from Javascript:-
[WebMethod]
public static string AddLikeMethod(int Id)
{
return UserControl.AddLike(Id);
}
Finally you can call this method as usual:-
$.ajax({
type: "POST",
url: "Default.aspx/AddLikeMethod",
data: "{ IDphoto :" + IDphoto + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.