4

I have ASP.NET web app that call some WebMethod from javascipt and fills textboxes. This is not all code, just example codesnippet

function dataApp(text) {

    var loc = window.location.href;
    $.ajax({
        type: "POST",
        url: loc + "/Recount",
        data: JSON.stringify({ 'data': text }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        error: function (xhr, ajaxOptions, thrownError) {
            $('#mycontrol').val("bla");
            $('#mycontrol2').val("bla");
            // ..
        }
    });
}


// here we get result from server and set some values in web UI
   function OnSuccess(response) {
    var obj = JSON.parse(response.d);

    $('#mycontrol1').val(obj.a);
    $('#mycontrol2').val(obj.b);
}

MyControl.ascx.cs:

[WebMethod]
public static string Recount(string data)
{
// ..
    return JsonString;
}

And it works good while Web Application Project, but now I want to migrate this code to Visual SP web part. And there is a problem connection to web method, in JS console I see(webpart added on default.aspx page):

POST http://server/web/default.aspx/Recount 500 (Internal Server Error)

How can I call my WebMethod from JS in Visual Webpart correctly?

The webpart is fully-featured, not sandboxed.

upd: user asked me an example of ascx file with webmethod, so I put it here:

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CurrencyRate.Layouts.CurrencyRate
{
    using System.Collections.Generic;
    using System.Globalization;
    using System.Net;
    using System.Web;
    using System.Web.Script.Serialization;
    using System.Web.Services;
    using System.Xml;

    public partial class CurrencyRate : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        ///  Update ratings from Yahoo API
        /// </summary>
        [WebMethod]
        public static string RefreshRates(string value)
        {
            try
            {
                // .. 
                return new JavaScriptSerializer().Serialize(
                            new
                                {
                                    error = false,
                                    // some values here
                                });
            }
            catch (Exception ex)
            {
                // ..

                return new JavaScriptSerializer().Serialize(
                        new
                            {
                                error = true,
                                // values
                            });
            }
        }
    }
}
  • Do you have a sample of WebMethos.aspx? – Danilo Barreto Feb 17 '15 at 13:06
8

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.

For these scenarios, we usually have an Application Page which defines all the WebMethods.. And than you can use the application page easily by simply referring to sitecollectionurl + /_layouts/ApplicationPageName.aspx/Recount

Something like:

$.ajax({
     type: "POST",
     url: siteUrl + "/_layouts/SolutionName/WebMethods.aspx/Recount",
     data: "{'data':'" + data + "'}",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     async: true,
     success: function (data) {
         response(data["d"]);
     },
     error: function (result) {
         //alert("Error");
     }
 });

where siteUrl is site collection Url, you can get it by using _spPageContextInfo.siteServerRelativeUrl or SPClientContext

References:

Embedding a WebMethod in a WebPart

Get a Site Collection and Web Path Using JavaScript in SharePoint 2013

  • Thank You! This method works cool! :) I used this sharepoint variable to find url: L_Menu_BaseUrl + "/_layouts/MySolution/MyWebMethods.aspx/Recount", – Gennady G May 7 '14 at 17:40

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.