如何通过JavaScript从ViewBag追加下拉列表并动态复制带递增ID的Div
问题:点击按钮追加含ViewBag绑定下拉列表的Div时出错
问题描述
需要实现JavaScript追加功能:点击Add按钮时复制整个Div并使其中的ID递增。目前文本框复制正常,但追加HTML中引入ViewBag绑定的下拉列表时出现错误。
错误原因
- ViewBag是服务器端语法:
asp-items="@ViewBag.relationship"属于Razor服务器端语法,仅在页面首次渲染时解析执行。通过JS动态追加的HTML不会被服务器重新处理,浏览器会将其视为普通字符串,导致下拉列表无法生成选项。 - 元素ID重复:动态生成的元素(如
#Milname、#insrel)ID固定,多次追加后会出现ID重复,引发DOM操作冲突。 - 模型绑定字段固定:
asp-for="InsuranceNomiee1Name"绑定固定字段,无法区分多个动态条目,后端无法正确接收多条数据。
解决方案
- 提前将ViewBag的下拉选项渲染为静态HTML片段,存储到页面隐藏容器中,动态追加时直接复用。
- 使用递增索引生成唯一的ID和模型绑定字段名(如
InsuranceNomiee${index}Name)。 - 调整模型结构,确保后端能接收多条动态生成的数据。
修改后的代码
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> <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> <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> `); 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
相关产品推荐
相关产品推荐

