ajax jquery .net导致“无法找到资源”。

时间:2013-01-07 14:50:18

标签: c# jquery .net ajax

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

2 个答案:

答案 0 :(得分:3)

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

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

然后,您可以使用以下网址上的jQuery调用此方法:http://localhost.com/[Controller]/HelloWorld

注意,在这里的示例中,我返回一个字符串 - 根据您的原始示例。也可以使用return Json(obj);

通过JSON返回对象

答案 1 :(得分:1)

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

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

相关问题