why jquery ajax method can only make a call to webmethod

469 Views Asked by At

While working with jQuery Ajax method, I came to know that the method can only make a call to webmethod or get/post of mvc. Why cannot I call the normal function using ajax method?

Example:

$.ajax({
    type: "POST",
    url: "CS.aspx/GetCurrentTime",
    data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    failure: function(response) {
        alert(response.d);
    }
});

Suppose, I am making a call to the method GetCurrentTime() of CS.aspx page, then i need to decorate the GetCurrentTime() with attribute WebMethod, to make a call from ajax method.

1

There are 1 best solutions below

0
On

What you get is expected behavior. The issue is not related to jQuery, but rather to the server-side code.

You normally request a resource via its URL to get that resource.

CS.aspx is the URL pointing to that page.

Using CS.aspx/GetCurrentTime actually is a different URL asking for a different resource.

And this is where WebMethodAttribute comes in. It tells ASP.NET that a new resource is available via the URL CS.aspx/GetCurrentTime and this way the ASP.NET runtime knows what to do when a request is made for that URL.

As a side note: ASP.NET MVC does not use .aspx in its URLs (not by default, at least). Better check your setup and get your things straight.

EDIT: If you were using MVC, you'd be in a controller (not a page) and you'd be writing actions (not methods). And no WebMethodAttribute would be necessary in that case because, by default, all public actions are available via the URLs configured in the RouteConfig.

The default route is this:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Hope this helps clearing your issues.