2

我正在尝试在 .net 中进行简单的 ajax 调用

有什么建议吗?

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

我在浏览器中这样调用 webmethod: http ://localhost.com/Ajax/WebService1.asmx/HelloWorld

这导致

“没有找到您要查的资源。”

可能是因为 url 语法。

我的路线设置如下:

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

如果我删除MapRoute,网络电话可以工作,但我网站的其余部分会失败。

有什么建议吗?

更新:我改为使用控制器。当我在浏览器中使用 url 调用它时,我在控制器中点击了断点。但不是当我运行这段代码时:

    <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);
      }
    });
  });
});

更新 2:我通过将行更改为

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

2 回答 2

3

因为您使用的是路由,所以我假设这是一个 MVC 网站?如果是这样,您应该ActionResult在控制器中使用 a 而不是WebMethod. 试试这个:

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

然后,您将在以下 URL 上使用 jQuery 调用它: http://localhost.com/[Controller]/HelloWorld

请注意,在此处的示例中,我将返回一个字符串 - 根据您的原始示例。也可以通过 JSON 返回一个对象,使用return Json(obj);

于 2013-01-07T14:54:46.040 回答
1

WebMethods 属于,ASP.NET WebForms而路由属于ASP.NET MVC. 你最好不要混合这两种技术。

在这种情况下,如果删除路由后一切都停止工作,那么大多数应用程序似乎都是 ASP.NET MVC。这意味着您想将 替换WebMethodController Action

于 2013-01-07T14:53:57.377 回答