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

如何实现点击按钮时每次生成_DetalheVendas.cshtml PartialView?

点击按钮动态加载PartialView的实现方案

我来帮你搞定这个需求!每次点击按钮就生成一个_DetalheVendas.cshtml PartialView,其实是ASP.NET里很常见的动态加载场景,跟着下面的步骤一步步来就行:

1. 先在后端Controller里加一个返回PartialView的Action

首先要给你的Controller添一个Action,专门用来返回这个PartialView——如果需要给PartialView传模型数据,也可以在这里处理:

public IActionResult GetDetalheVendas()
{
    // 要是你的PartialView需要模型,就在这里初始化并传递
    // var viewModel = new DetalheVendasViewModel();
    return PartialView("_DetalheVendas");
}

2. 在页面上准备一个存放PartialView的容器

在你的按钮下方加一个空容器,每次加载的PartialView都会追加到这里:

<div style="padding-bottom: 15px;"> 
    <button id="btnNovaFormaPagamento" type="button" class="btn btn-primary">Nova Forma de Pagamento</button> 
</div>
<!-- 新增这个容器用来装每次生成的PartialView -->
<div id="partialViewsContainer"></div>

3. 写前端点击事件的AJAX逻辑

接下来用JS监听按钮的点击事件,每次点击就请求后端的Action,把返回的HTML插入到容器里。这里给你两种写法,选你顺手的就行:

用jQuery的写法(如果项目里已经引入jQuery)

$(document).ready(function() {
    $('#btnNovaFormaPagamento').click(function() {
        $.ajax({
            // 替换成你的Controller名称,比如你的Controller叫VendasController,就写"Vendas"
            url: '@Url.Action("GetDetalheVendas", "YourControllerName")',
            type: 'GET',
            success: function(htmlResult) {
                // 把返回的PartialView HTML追加到容器里
                $('#partialViewsContainer').append(htmlResult);
            },
            error: function(xhr, status, err) {
                console.error('加载PartialView出错啦:', err);
            }
        });
    });
});

原生JS的写法(不需要jQuery)

document.addEventListener('DOMContentLoaded', function() {
    const addButton = document.getElementById('btnNovaFormaPagamento');
    const container = document.getElementById('partialViewsContainer');

    addButton.addEventListener('click', async function() {
        try {
            // 同样要替换成你的Controller名称
            const response = await fetch('@Url.Action("GetDetalheVendas", "YourControllerName")');
            if (!response.ok) throw new Error('请求失败');
            
            const partialHtml = await response.text();
            // 把新的PartialView加到容器末尾
            container.insertAdjacentHTML('beforeend', partialHtml);
        } catch (error) {
            console.error('加载PartialView出错:', error);
        }
    });
});

一些要注意的小细节

  • 一定要把代码里的YourControllerName替换成你实际的Controller类名(比如Vendas、Pagamentos这类)。
  • 如果你的_DetalheVendas.cshtml需要绑定模型数据,就在后端的GetDetalheVendas Action里初始化好模型,再传给PartialView方法就行,前端加载时会自动渲染带数据的视图。
  • 如果后续需要给每个生成的PartialView加删除功能,可以在渲染PartialView的时候给每个视图的外层容器加一个唯一ID或者类名,方便后续操作。

内容的提问来源于stack exchange,提问作者Geovanna Monteiro Scabio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:33:00