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

如何使用jQuery实现不刷新页面仅刷新指定view component组件

实现View Component局部刷新的两种方案

首先先对原有视图做基础改造,给View Component包裹定位容器:

<div id="userProfileContainer">
    @await Component.InvokeAsync("UserProfileCard")
</div>
<!-- 刷新按钮 -->
<button id="refreshBtn">刷新用户卡片</button>

方案1:使用原生jQuery Ajax实现

步骤1:新增后端接口返回ViewComponent内容

在对应控制器中添加接口,用于返回组件渲染后的HTML:

public IActionResult RefreshUserProfile()
{
    // 若组件需要传参,可在此处接收参数并传入InvokeAsync的第二个参数
    return ViewComponent("UserProfileCard");
}

步骤2:编写jQuery Ajax请求逻辑

页面引入jQuery后添加如下代码:

$(function(){
    $('#refreshBtn').click(function(){
        $.ajax({
            url: '@Url.Action("RefreshUserProfile")',
            type: 'GET',
            success: function(res){
                $('#userProfileContainer').html(res);
            },
            error: function(){
                alert('刷新失败,请稍后重试');
            }
        });
    });
});

方案2:使用jQuery Unobtrusive Ajax实现

步骤1:引入依赖脚本

确保页面已引入jQuery和jquery.unobtrusive-ajax.js脚本。

步骤2:给按钮添加Unobtrusive Ajax标记

无需额外写JS代码,直接修改按钮属性即可:

<button 
    data-ajax="true" 
    data-ajax-url="@Url.Action("RefreshUserProfile")"
    data-ajax-method="GET"
    data-ajax-mode="replace"
    data-ajax-update="#userProfileContainer"
    data-ajax-loading="#loadingTip"
>
    刷新用户卡片
</button>
<!-- 可选:加载提示 -->
<div id="loadingTip" style="display:none">加载中...</div>

所有data-ajax开头的属性由Unobtrusive Ajax自动解析执行,无需手动绑定点击事件。


内容的提问来源于stack exchange,提问作者Regestea

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:09:01