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

ViewBag绑定SelectList后ejs-combobox下拉框显示空白问题

解决Syncfusion ComboBox绑定ViewBag数据显示空白问题

问题原因

你在控制器中用SelectList包装了分类集合,生成的每个列表项的属性是Text和Value,而非原实体的Name和CategoryId。但前端ComboBox配置的fields-text="Name"和fields-value="CategoryId"找不到对应属性,导致下拉框显示空白。

两种解决方案

方案一:直接传递实体集合(推荐)

不需要用SelectList包装,直接把数据库查询到的分类实体列表传给ViewBag,前端保持原字段配置:

控制器代码修改:

public IActionResult Create()
{
    var categories = _context.Categories.ToList();
    ViewBag.Categories = categories; // 直接传递实体集合
    
    return View(new Exercise());
}

前端代码保持不变:

<div class="form-group">
     <ejs-combobox id="categories" dataSource="@ViewBag.Categories" fields-text="Name" fields-value="CategoryId" placeholder="Select Category" popupHeight="220px" style="color:#fff">
     </ejs-combobox>
     <span asp-validation-for="Category" class="text-danger"></span>
</div>

方案二:修改前端字段映射匹配SelectList属性

如果要保留SelectList包装,前端需要将fields-text和fields-value改为Text和Value,对应SelectList项的属性:

前端代码修改:

<div class="form-group">
     <ejs-combobox id="categories" dataSource="@ViewBag.Categories" fields-text="Text" fields-value="Value" placeholder="Select Category" popupHeight="220px" style="color:#fff">
     </ejs-combobox>
     <span asp-validation-for="Category" class="text-danger"></span>
</div>

控制器代码无需修改。

额外提示

若要实现表单提交时模型的Category属性正确绑定,需给ComboBox添加name="Category"属性:

<ejs-combobox id="categories" name="Category" dataSource="@ViewBag.Categories" fields-text="Name" fields-value="CategoryId" placeholder="Select Category" popupHeight="220px" style="color:#fff">
</ejs-combobox>

内容的提问来源于stack exchange,提问作者Tomáš grzeho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:17:17