【问题标题】:jQuery AJAX works to return mvc 3 partial view but jQuery load doesn'tjQuery AJAX 可以返回 mvc 3 部分视图,但 jQuery 加载不
【发布时间】:2011-07-25 03:48:54
【问题描述】:

我正在尝试在 MVC 3 中使用部分视图填充 div。我的控制器如下所示:

[HttpPost]
public ActionResult GetCustomerList(string searchString)
{
    var custService = new CustomerViewModels();
    var custListVM = custService.GetSearchList(searchString);

    return PartialView("GetCustomersList", custListVM);
}

我的 jQuery 调用如下所示:

function getCustomerList(searchCriteria) {
    $.ajax({
        url: 'Home/GetCustomerList',
        type: 'POST',
        async: false,
        data: { searchString: searchCriteria },
        success: function (result) {
            $("#customerTabBody").html(result);
        }
    });
};

它工作正常。我开始怀疑我是否可以使用 jQuery 加载方法用更少的代码做同样的事情,然后写了这个:

function getCustomerList(searchCriteria) {
    $("#customerTabBody").load('Home/GetCustomerList', { searchString: searchCriteria });
};

它返回一个错误,指出找不到资源。我试过使用@Url.Action,但它编码了我硬编码的相同控制器路径。在 Firebug 中,我可以看到发布到的 URL 是相同的,并且 searchString 参数在两个实例中的格式相同。

有什么区别 - 为什么加载不起作用?

谢谢

【问题讨论】:

  • 你为什么在 $.ajax 调用中设置 async: false ?
  • 我需要在等待响应时阻止用户继续输入字符。

标签: jquery asp.net-mvc ajax load


【解决方案1】:

load 的 Jquery 文档说...

The POST method is used if data is provided as an object; otherwise, GET is assumed.

由于您将数据作为对象传递,因此根据文档,它必须是 post call。此外,您通过 $.ajax 从控制器获取所需的数据,因此控制器操作方法似乎没问题。使用 load 发送 ajax 请求时可能会出现一些错误。你可以在萤火虫中检查这个。

【讨论】:

  • 我使用 Firebog 仔细查看了 post 数据,并且目标控制器 URL 在两者中相同,searchString 键值对也是如此。
  • 在firebug中查看ajax请求的响应
【解决方案2】:

你可以试试这个看看它是否有效?

function getCustomerList(searchCriteria) {

         $('#customerTabBody').load('@Url.Action("GetCustomerList", "Home")', { 'searchString': searchCriteria });

};

【讨论】:

    【解决方案3】:

    我相当肯定您的.load() 调用执行的是GET 请求而不是POST。 MVC 3 和大多数其他 .NET AJAX 事务(装饰为 WebMethod 的方法,例如 Web 服务和页面方法)需要 POST 数据。在这种情况下,您只需要坚持有效的方法。正如您在 $.ajax() 调用中看到的,请求方法是 POST。如果您想简写一些代码,请使用.ajaxSetup() 结合.post()

    【讨论】:

    • asp.net mvc 控制器操作方法不需要发布每个 ajax 请求,除非它们用HttpPost 装饰。唯一的例外是返回 json 结果的方法。即使在这种情况下,您也可以允许 Get 请求,例如 return Json(data,JsonRequestBehavior.AllowGet);
    • 其实我也想知道。我尝试用 [HttpGet] 装饰我的控制器方法,但它仍然找不到资源,所以我认为这无关紧要。我还查看了 Firebug 中的帖子和响应流量,它显示了由 jQuery 加载生成的回发,它显示为帖子(而不是获取)。
    猜你喜欢
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多