1

I have a very simple page and a [WebMethod] inside it which returns a simple message. I would like to show this message through $.ajax on client side. however my website is using rewrites rules so my url becomes readable to user.

EX: Actual webpage: www.mysite.com/about // which has about folder and a user control inside it

there is no aspx page for this instead i am using a method which gets a webpage data which is actual html page and show the content on user control.

here is Jquery part.

$(document).ready(function () {
    $('.info a').click(function () {
        $.ajax({
            type: 'POST',
            url: '/about/showServer', //which url to put here
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                alert("result.d");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            },
        });
    });
}); 

C#

[WebMethod] // this method is in the user control
      public static string showServer()
      {
            return "Hello from server";
      }

How to call this method from client using $.ajax

appreciate your time and help.

EDITS

I have this structure for my website

mysite.com/about

/about/defualt.aspx --> which loads the user controls

user controls resides in

mysite.com/ConLib/Custom/about.ascx/showServer

So i set it to like this

url: '/ConLib/Custom/about.ascx/showServer',

BUT i see error in chrome developer tool in XHR request "404 error" because when you type mysite.com/conlib/blah blah ..reqrites does not allows this and throws 404 error..

patel.milanb
  • 5,822
  • 15
  • 56
  • 92

3 Answers3

1

Your ajax success method should be this:

alert(result.d);

Instead of this:

success: function (result) {
    alert("result.d");
}

and url should be:

url: "Default.ascx/showServer",   // UserControlPage/MethodName
palaѕн
  • 72,112
  • 17
  • 116
  • 136
1

you need to decorate your web method

  [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json)]
  public static string showServer()
  {
        return "Hello from server";
  }
Clinton Ward
  • 2,441
  • 1
  • 22
  • 26
1

If your WebMethod is inside a User Control, then it needs to be moved to the ASPX page. See this post:

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

The url: param should be in the form of '/MyPage.aspx/showServer'

Community
  • 1
  • 1
Rob
  • 5,578
  • 3
  • 23
  • 28