You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用form标签通过jQuery Unobtrusive Ajax调用控制器,并在自定义Ajax请求中使用data-ajax系列属性

手动实现Unobtrusive Ajax属性的自定义Ajax方案

好问题!你提到的data-ajax、data-ajax-mode和data-ajax-update是ASP.NET Unobtrusive Ajax库提供的便捷封装,现在要在自定义jQuery Ajax函数里实现同样的效果,其实就是把这些属性对应的逻辑手动写到请求的回调中即可,我来给你拆解并修改代码:

先明确每个属性的实际作用

  • data-ajax="true":本质是启用Ajax提交(而非传统表单刷新),这一点你已经通过直接调用$.ajax做到了,不需要额外处理。
  • data-ajax-mode="replace":指定服务器返回的HTML内容对目标元素的更新方式,replace意味着直接替换目标元素的内部内容。
  • data-ajax-update="#ProductList":指定接收更新的DOM元素选择器。

修改后的自定义Ajax函数

var Categories = function (Key, Length) {
    $.ajax({
        type: "POST",
        url: "/ShopGrid/PartialAction",
        data: { 
            GrpKey: array,
            // 注意:原表单里的name输入框值需要手动获取并传递,和表单提交逻辑一致
            name: $('input[name="name"]').val()
        },
        success: function (response) {
            // 实现data-ajax-update和data-ajax-mode="replace"的核心逻辑
            var targetElement = $('#ProductList');
            // replace模式:直接替换目标元素的内部HTML
            targetElement.html(response);

            // 扩展:如果需要其他mode,对应jQuery方法如下
            // data-ajax-mode="insertBefore" → targetElement.before(response);
            // data-ajax-mode="insertAfter" → targetElement.after(response);
            // data-ajax-mode="replace-with" → targetElement.replaceWith(response);
        },
        error: function(xhr, status, error) {
            // 可选:添加错误处理,模拟Unobtrusive Ajax的错误提示逻辑
            console.error('请求失败:', error);
            // 也可以在这里给用户显示友好提示,比如$('#ProductList').html('<p>加载失败,请重试</p>');
        }
    });
};

额外注意点

  1. 原表单中的name输入框值需要手动获取并添加到data参数中,否则控制器无法接收到这个参数(表单提交时会自动携带所有表单控件的值,自定义Ajax需要手动处理)。
  2. 如果需要模拟Unobtrusive Ajax的加载状态提示,可以在beforeSend回调中显示加载动画,在complete回调中隐藏它:
    beforeSend: function() {
        $('#ProductList').html('<p>加载中...</p>');
    },
    complete: function() {
        // 可以在这里清理加载状态
    }
    

内容的提问来源于stack exchange,提问作者H.M.Mubashir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:02:40