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

如何通过JavaScript从ViewBag追加下拉列表并动态复制带递增ID的Div

问题:点击按钮追加含ViewBag绑定下拉列表的Div时出错

问题描述

需要实现JavaScript追加功能:点击Add按钮时复制整个Div并使其中的ID递增。目前文本框复制正常,但追加HTML中引入ViewBag绑定的下拉列表时出现错误。

错误原因

  1. ViewBag是服务器端语法:asp-items="@ViewBag.relationship"属于Razor服务器端语法,仅在页面首次渲染时解析执行。通过JS动态追加的HTML不会被服务器重新处理,浏览器会将其视为普通字符串,导致下拉列表无法生成选项。
  2. 元素ID重复:动态生成的元素(如#Milname、#insrel)ID固定,多次追加后会出现ID重复,引发DOM操作冲突。
  3. 模型绑定字段固定:asp-for="InsuranceNomiee1Name"绑定固定字段,无法区分多个动态条目,后端无法正确接收多条数据。

解决方案

  1. 提前将ViewBag的下拉选项渲染为静态HTML片段,存储到页面隐藏容器中,动态追加时直接复用。
  2. 使用递增索引生成唯一的ID和模型绑定字段名(如InsuranceNomiee${index}Name)。
  3. 调整模型结构,确保后端能接收多条动态生成的数据。

修改后的代码

HTML 代码

<div class="container">
    <div class="row">
        <div id="sibs" class="row mb-2 "></div>
        <!-- 提前渲染下拉选项模板,用隐藏容器存放 -->
        <div id="relationship-options-template" style="display:none">
            @foreach (var item in ViewBag.relationship as IEnumerable<SelectListItem>)
            {
                <option value="@item.Value">@item.Text</option>
            }
        </div>
        <button type="button" class="btn btn-md btn-info ml-2 button-icon rounded-small add_info">
            <i class="fa fa-user-plus" aria-hidden="true"></i> Add 
        </button>
    </div>
</div>

JavaScript 代码

var index = 1; // 用于生成唯一的索引后缀
$(document).ready(function () {
    // 获取提前渲染好的下拉选项HTML
    var relationshipOptions = $('#relationship-options-template').html();

    $(".add_info").click(function () {
        $("#sibs").append(`
            <div class="border-5">
                <h3>Insurance Dependent (${index}) </h3>
                &nbsp;&nbsp;&nbsp;
                <div class="row mb-2">
                    <label class="col-sm-2 col-form-label">Dependent Name <span style="color:red;font-size:20px">*</span></label>
                    <div class="col-sm-3">
                        <input asp-for="InsuranceNomiee${index}Name" class="form-control" placeholder="James" id="Milname-${index}" required />
                        <span asp-validation-for="InsuranceNomiee${index}Name" class="text-danger"></span>
                    </div>
                </div>
                &nbsp;&nbsp;
                <div class="row mb-2 ">
                    <label class="col-sm-2 col-form-label">Relationship With Dependent <span style="color:red;font-size:20px">*</span></label>
                    <div class="col-sm-3">
                        <select asp-for="InsuranceNomiee${index}Relationship" class="form-control" id="insrel-${index}" required>
                            ${relationshipOptions}
                        </select>
                        <span asp-validation-for="InsuranceNomiee${index}Relationship" class="text-danger"></span>
                    </div>
                </div>
            </div>
            &nbsp;&nbsp;&nbsp;&nbsp;
        `);
        index++; // 索引自增,保证下次生成唯一的字段和ID
    });
});

后端模型调整说明

后端需要定义可接收多条数据的属性,示例如下:

// 使用列表接收多个依赖人数据
public List<string> InsuranceNomieeName { get; set; }
public List<string> InsuranceNomieeRelationship { get; set; }

// 或者使用自定义实体类
public List<Dependent> Dependents { get; set; }
public class Dependent 
{
    public string Name { get; set; }
    public string Relationship { get; set; }
}

若使用实体类,前端asp-for需改为asp-for="Dependents[${index}].Name"这类形式,确保模型绑定正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:54:54