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

.NET Core 6:如何用jQuery更新ViewModel生成的动态列表并同步模型?

问题原因

ASP.NET Core的模型绑定对集合类型的表单元素有严格的命名规则:必须遵循集合属性名[索引].子属性名的格式(比如UserHobbies[0].IsChecked)。你用jQuery追加的HTML如果没有严格匹配这个命名格式,后端控制器就无法将这些新增项映射到UserDTO.UserHobbies集合中。

Razor的asp-for标签助手会自动生成符合规则的name和id属性,但手动拼接HTML时很容易忽略这一点,导致新增项的参数无法被模型绑定识别。

解决方案

不需要“更新Razor模型”(Razor是服务器端渲染逻辑,客户端无法直接修改),只要确保动态添加的表单元素name属性符合模型绑定规则即可,以下是两种可行的实现方式:

方式一:基于当前最大索引递增生成命名

  1. 先获取现有爱好项的数量(即最大索引值):
var maxIndex = $('#hobbies .hobby-item').length;
  1. 构造符合规则的HTML元素并追加(假设通过AJAX获取到新爱好数据newHobby):
var newHobby = { HobbyID: 10, HobbyDescription: '攀岩', HobbyCategoryId: 2 };

var html = `<div class="hobby-item col-md-6">
               <input type="checkbox" name="UserHobbies[${maxIndex}].IsChecked" id="UserHobbies_${maxIndex}__IsChecked" />
               <label class="attrChk" for="UserHobbies_${maxIndex}__IsChecked">${newHobby.HobbyDescription}</label>
               <input type="hidden" name="UserHobbies[${maxIndex}].HobbyID" value="${newHobby.HobbyID}" />
               <input type="hidden" name="UserHobbies[${maxIndex}].HobbyDescription" value="${newHobby.HobbyDescription}" />
               <input type="hidden" name="UserHobbies[${maxIndex}].HobbyCategoryId" value="${newHobby.HobbyCategoryId}" />
            </div>`;

$('#hobbies').append(html);

方式二:使用显式唯一索引(支持非连续场景)

如果需要支持删除中间项后新增的场景,可以给每个新增项分配唯一数字索引(比如时间戳),只要name属性中的索引唯一即可:

// 用时间戳生成唯一索引,避免重复
var uniqueIndex = Date.now();
var html = `<div class="hobby-item col-md-6">
               <input type="checkbox" name="UserHobbies[${uniqueIndex}].IsChecked" id="UserHobbies_${uniqueIndex}__IsChecked" />
               <label class="attrChk" for="UserHobbies_${uniqueIndex}__IsChecked">${newHobby.HobbyDescription}</label>
               <input type="hidden" name="UserHobbies[${uniqueIndex}].HobbyID" value="${newHobby.HobbyID}" />
               <input type="hidden" name="UserHobbies[${uniqueIndex}].HobbyDescription" value="${newHobby.HobbyDescription}" />
               <input type="hidden" name="UserHobbies[${uniqueIndex}].HobbyCategoryId" value="${newHobby.HobbyCategoryId}" />
            </div>`;

$('#hobbies').append(html);
关键注意事项
  • 保证同一项的索引一致:同一个爱好项的IsChecked、HobbyID等字段,name属性中的索引必须完全相同,否则模型绑定会视为不同的集合项。
  • 检查提交参数格式:可以在浏览器开发者工具的「网络」标签中查看表单提交的Form Data,确认新增项的参数格式为UserHobbies[索引].子属性名=值。
  • 不要遗漏隐藏字段:和原Razor代码一致,新增项的HobbyID、HobbyDescription等字段也需要用隐藏字段提交,否则后端无法获取这些值。

内容的提问来源于stack exchange,提问作者N.MORR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:55:20