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

ASP.NET MVC同父视图下分部视图间传递数据并更新视图的方法

实现无刷新更新HeadphonesList分部视图

1. 改造HeadphonesFilters分部视图

将过滤器封装为表单,确保输入控件的name属性与Filter方法的参数名一致,方便后续提交数据:

@model dynamic
<form id="filter-form">
    <div class="mb-3">
        <label>最低价格</label>
        <input type="number" name="minPrice" value="@Model.minPrice" class="form-control" />
    </div>
    <div class="mb-3">
        <label>最高价格</label>
        <input type="number" name="maxPrice" value="@Model.maxPrice" class="form-control" />
    </div>
    <button type="submit" class="btn btn-primary">筛选</button>
</form>

2. 添加AJAX异步提交脚本(在Index视图中)

通过jQuery监听表单提交事件,阻止默认页面跳转,异步请求Filter接口并更新目标分部视图:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(function() {
        $('#filter-form').submit(function(e) {
            // 阻止表单默认提交行为
            e.preventDefault();
            
            // 序列化表单数据
            var formData = $(this).serialize();
            
            // 发送AJAX请求
            $.ajax({
                url: '@Url.Action("Filter", "Headphones")',
                type: 'GET',
                data: formData,
                success: function(html) {
                    // 用返回的分部视图HTML替换容器内容
                    $('#headphones-list').html(html);
                },
                error: function(err) {
                    console.error('筛选请求失败:', err);
                }
            });
        });
    });
</script>

3. 完善初始数据加载(可选)

为了让页面初始加载时HeadphonesList有数据,修改HeadphonesController的Index方法:

public ActionResult Index()
{
    // 加载全部耳机数据作为初始列表
    var initialHeadphones = service.GetHeadphones().ToList();
    return View(initialHeadphones);
}

同时更新Index视图中分部视图的调用:

<div class="col-8" id="headphones-list">
    @Html.Partial("HeadphonesList", Model)
</div>

说明

你的现有Filter方法无需修改,它已经正确返回HeadphonesList分部视图。通过AJAX异步请求,就能实现点击筛选按钮后,仅更新页面右侧的耳机列表区域,不会跳转新页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:55:22