问题描述:

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..

网友答案:

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
网友答案:

you need to decorate your web method

  [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json)]
  public static string showServer()
  {
        return "Hello from server";
  }
网友答案:

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

Call webMethod in User control

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

相关阅读:
Top