Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an ASP.NET WebMethod in a UserControl (.ascx)

Is it possible to place a WebMethod in an ascx.cs file (for a UserControl) and then call it from client-side jQuery code?

For some reasons I can't place the WebMethod code in an .asmx or .aspx file.

Example: In ArticleList.ascx.cs I have the following code:

[WebMethod] public static string HelloWorld() {     return "helloWorld"; } 

In ArticleList.ascx file there I have the call to the WebMethod as follows:

$.ajax({             type: "POST",             contentType: "application/json; charset=utf-8",             data: "{}",             dataFilter: function(data)//makes it work with 2.0 or 3.5 .net             {                 var msg;                 if (typeof (JSON) !== 'undefined' &&                 typeof (JSON.parse) === 'function')                     msg = JSON.parse(data);                 else                     msg = eval('(' + data + ')');                 if (msg.hasOwnProperty('d'))                     return msg.d;                 else                     return msg;             },             url: "ArticleList.ascx/HelloWorld",             success: function(msg) {                 alert(msg);             }         }); 

and the error from firebug is:

<html> <head>     <title>This type of page is not served.</title> 

How can I sucessfully call the server-side WebMethod from my client-side jQuery code?

like image 854
gruber Avatar asked Apr 12 '11 15:04

gruber


People also ask

What is the use of WebMethod in asp net?

The WebMethod attribute is added to each method we want to expose as a Web Service. ASP.NET makes it possible to map traditional methods to Web Service operations through the System. Web. Services.

What is UserControl in asp net?

User controls. User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it. Custom controls. A custom control is a class that you write that derives from Control or WebControl.


1 Answers

WebMethod should be static. So, You can put it in the user control and add a method in the page to call it.

Edit:

You can not call a web method through a user control because it'll be automatically rendered inside the page.

The web method which you have in the user control:

public static string HelloWorld() {     return "helloWOrld"; } 

In the Page class add the web method:

[WebMethod] public static string HelloWorld() {     return ArticleList.HelloWorld(); // call the method which                                       // exists in the user control } 
like image 106
Homam Avatar answered Sep 21 '22 18:09

Homam