【问题标题】:ajax jquery .net results in "The resource cannot be found."ajax jquery .net 导致“找不到资源”。
【发布时间】:2013-01-07 14:50:18
【问题描述】:

我正在尝试在 .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'}",

【问题讨论】:

    标签: c# jquery .net ajax


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 谢谢,这解决了问题,但我不确定我的 jquery 代码是否可以调用控制器
    • @Anders 可以——就像任何锚一样。另外,如果有帮助,请不要忘记接受此答案。
    【解决方案2】:

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

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

    【讨论】:

    • 谢谢。用一个新问题更新了我的答案:-)
    猜你喜欢
    • 2013-08-03
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2021-05-04
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多