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

如何将GridView中记录的id等属性传递给Bootstrap Modal?

实现方案

1. 修改GridView触发链接,添加数据属性

在你原来触发模态框的Html::a方法的配置项里,新增两个自定义data-*属性,用于存储当前行的文件ID和文件名:

Html::a('<i class="glyphicon glyphicon-link"></i>', '#', [
    'data-toggle'=>'modal',
    'data-target'=>'#modalShare',
    'data-id' => $model->id, // 存储当前行记录ID
    'data-name' => $model->name // 替换为你实际存储文件名的字段名
])

2. 调整模态框基础结构

移除原来错误的ID输出,模态框标题和内容区域留空,等待JS动态注入:

<!-- LinkModal -->
<div class="modal fade" id="modalShare" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="myModalLabel"></h4>
            </div>
            <div class="modal-body">
            </div>
        </div>
    </div>
</div>

3. 添加JS逻辑动态注入数据

监听Bootstrap模态框的show.bs.modal事件,读取触发按钮上的自定义数据,更新到模态框中,需要的话还可以通过ajax加载对应ID的业务内容:

$(function() {
    // 监听模态框打开事件
    $(document).on('show.bs.modal', '#modalShare', function (event) {
        const triggerBtn = $(event.relatedTarget);
        // 读取行数据
        const fileId = triggerBtn.data('id');
        const fileName = triggerBtn.data('name');
        const modal = $(this);
        
        // 更新模态框标题
        modal.find('.modal-title').text('共享文件:' + fileName);
        // 把ID存在模态框实例上,方便后续提交等逻辑调用
        modal.data('current-file-id', fileId);

        // 如果需要加载对应ID的共享配置表单,添加这段ajax请求
        $.get('<?= \yii\helpers\Url::to(['file/get-share-form']) ?>', {id: fileId}, function(html) {
            modal.find('.modal-body').html(html);
        });
    });

    // 示例:模态框内表单提交逻辑,可直接读取存储的文件ID
    $(document).on('submit', '#share-form', function(e) {
        e.preventDefault();
        const fileId = $('#modalShare').data('current-file-id');
        // 后续提交表单逻辑,把fileId和表单数据一起传给后端接口即可
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:15:02