Anders
Anders

Reputation: 163

ajax jquery .net results in "The resource cannot be found."

I'm trying to do a simple ajax call in .net

Any advice?

[WebMethod]
public string HelloWorld()
{
    return "Hello World";
}

I call the webmethod in my browser like this: http://localhost.com/Ajax/WebService1.asmx/HelloWorld

Which results in

"The resource cannot be found."

Probably because of the url syntax.

My routes are setup like:

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

If I delete the MapRoute, the webcall works, but the rest of my website fails.

Any advice?

Update: I changed to use a controller. When I call it with a url in my browser I hit my breakpoint in the controller. But not when I run this code:

    <div id="Result">
        Kig her!
    </div>



@section javascript {
    $(function () {
        $("#FirstReminder").datepicker();
        $("#EndDate").datepicker();
    });

$(document).ready(function() {
  // Add the page method call as an onclick handler for the div.
  $("#Result").click(function() {
    alert('kkk');
    $.ajax({
      type: "POST",
      url: "AjaxWorkflow/GetSteps",
      data: {workflowId: "1", workflowStep: "test"},
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        // Replace the div's content with the page method's return.
        $("#Result").text(msg.d);
      }
    });
  });
});

Update 2: I solved it by changing the line to

          data: "{workflowId: '1', workflowStep: 'test'}",

Upvotes: 2

Views: 2608

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337580

Because you are using routing, I assume this is an MVC website? If so you should use an ActionResult in your controller instead of a WebMethod. Try this:

public string HelloWorld()
{
    return Content("Hello World");
}

You would then call this using jQuery on the following URL: http://localhost.com/[Controller]/HelloWorld

Note, in the example here I am returning a string - as per your original example. It is also possible to return an object via JSON, using return Json(obj);

Upvotes: 3

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

WebMethods belong to ASP.NET WebForms while the routing belongs to ASP.NET MVC. You'd better not mix the two technologies.

In this case most of the application seems to be ASP.NET MVC if after removing the routing everything stops working. That means that you want to replace the WebMethod with a Controller Action.

Upvotes: 1

Related Questions