0

I have a SharePoint 2010 web part on a page in a site. I'm trying to use AJAX to call my C# cs method to retrieve data, so I can display it in the web part.

I did have an example below, however, it returns the page default.aspx, instead of the result of 2 (within the function).

Here's my code:

//webpart.ascx.cs
[WebMethod]
public static int calculate(string name)
{
   Console.Write(name);
   int result = 1 + 1;
   return result;
}

//webpart.ascx
(function ($) {        
    var url = "/Pages/default.aspx/calculate"
    $.ajax({
        type: 'POST',
        url: url,
        data: { name: "testing" },
        headers: { "accept": "application/json;odata=verbose" },
        success: function (data) {
            console.log("success");
            console.log(data);
        },
        error: function (error) {
            console.log(error);
        }
    });

})(jQuery);

How can I call an AJAX call within the web part (SharePoint with .ascx file)?

Thanks.

  • you can always use the CEWP to inject the javascript, no need to house it in it's own ascx – Mike Jan 22 '17 at 2:35
0

You cant add a WebMethod to a webpart. A webpart is a server control and outputs html to the page. If you want to use webmethods I would create a web service and consume this in the webpart or by other pages / controls

But you can create an Application Page (like WebMethods.aspx). Something like this:

using System.Web.Services;
public partial class WebMethods : LayoutsPageBase
{
    [WebMethod]
    public static int calculate(string name)
    {
        //Console.Write(name);
        int result = 1 + 1;
        return result;
    }
}

Use one of this urls:

_spPageContextInfo.webAbsoluteUrl + "/_layouts/14/<project name folder>/<pagename>.aspx/<webmethod>"
_spPageContextInfo.webAbsoluteUrl + "/_layouts/14/<pagename>.aspx/<webmethod>"

Replace <project name folder> with your folder name. This is optional, it depends on where you position the page within your visual studio project structure.
Replace <pagename> with your page name.
Replace <webmethod> with your web method name.

And make the call like this:

//webpart.ascx
(function ($) {
    var url = _spPageContextInfo.webAbsoluteUrl + "/_layouts/14/<project name folder>/WebMethods.aspx/calculate"
    $.ajax({
        type: 'POST',
        url: url,
        data: { name: "testing" },
        headers: { "accept": "application/json;odata=verbose" },
        success: function (data) {
            console.log("success");
            console.log(data);
        },
        error: function (error) {
            console.log(error);
        }
    });

})(jQuery);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.