使用ViewBag生成动态下拉列表时始终返回undefined问题求助
问题排查与解决:ViewBag绑定下拉列表显示undefined
问题根源
你序列化的ViewBag.ToolCategories是SelectList类型,它的JSON结构并非直接的分类实体数组,而是包含Items、SelectedValue等属性的对象。直接遍历jsonObj无法获取CategoryId和CategoryName,导致出现undefined。
解决方案
方法一:后端传递实体列表(推荐)
修改后端代码,直接将分类实体集合存入ViewBag,而非封装成SelectList:
private void ToolCategories(object selectedcat = null) { var catQuery = from d in db.Toolcategories where d.In == "AD" orderby d.CategoryName select d; // 存入实体列表,而非SelectList ViewBag.ToolCategoryList = catQuery.ToList(); }
前端对应修改序列化对象及遍历逻辑,同时修正拼写错误并补充DOM挂载代码:
@using System.Text.Json; <script> var resin = document.createElement("div"); resin.setAttribute("class", "col-md-4"); var resinGrup = document.createElement("div"); resinGrup.setAttribute("class", "form-group"); <!-- 修正form-grup拼写错误 --> var resinLabel = document.createElement("label"); resinLabel.setAttribute("class", "form-label fs-6"); resinLabel.innerHTML = "Tool"; // 序列化实体列表 var jsonObj = @Html.Raw(JsonSerializer.Serialize(ViewBag.ToolCategoryList)); var resinSelect = document.createElement("select"); resinSelect.setAttribute("id", "CategoryId"); resinSelect.setAttribute("class", "form-control"); resinSelect.setAttribute("required", ""); resinSelect.setAttribute("name", `[${toolID}].ToolCategories`); // 遍历实体数组 $.each(jsonObj, function (index, category) { var option = document.createElement("option"); option.value = category.CategoryId; option.text = category.CategoryName; resinSelect.append(option); }) // 将创建的元素挂载到DOM(需确保页面存在对应容器) resinGrup.appendChild(resinLabel); resinGrup.appendChild(resinSelect); resin.appendChild(resinGrup); document.getElementById("toolContainer").appendChild(resin); </script>
方法二:保留SelectList,前端访问Items属性
若坚持使用SelectList,需遍历其Items属性,且注意SelectList的Item对象属性为Text和Value:
@using System.Text.Json; <script> var resin = document.createElement("div"); resin.setAttribute("class", "col-md-4"); var resinGrup = document.createElement("div"); resinGrup.setAttribute("class", "form-group"); <!-- 修正拼写错误 --> var resinLabel = document.createElement("label"); resinLabel.setAttribute("class", "form-label fs-6"); resinLabel.innerHTML = "Tool"; var jsonObj = @Html.Raw(JsonSerializer.Serialize(ViewBag.ToolCategories)); var resinSelect = document.createElement("select"); resinSelect.setAttribute("id", "CategoryId"); resinSelect.setAttribute("class", "form-control"); resinSelect.setAttribute("required", ""); resinSelect.setAttribute("name", `[${toolID}].ToolCategories`); // 遍历SelectList的Items属性 $.each(jsonObj.Items, function (index, item) { var option = document.createElement("option"); option.value = item.Value; option.text = item.Text; resinSelect.append(option); }) // 挂载到DOM resinGrup.appendChild(resinLabel); resinGrup.appendChild(resinSelect); resin.appendChild(resinGrup); document.getElementById("toolContainer").appendChild(resin); </script>
额外注意事项
- 检查
toolID变量是否已正确定义,避免name属性生成异常 - 动态创建的元素必须挂载到DOM中,否则无法在页面显示
内容的提问来源于stack exchange,提问作者taufiqullr
相关产品推荐
相关产品推荐

