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

ASP.NET Core MVC 视图中通过ViewModel填充Select控件报错求助

问题原因及修复方案

1. 标签属性拼写错误

你当前select标签使用的app-for是无效属性,ASP.NET Core MVC的标签助手绑定字段对应属性为asp-for,且绑定路径需要与label保持一致,填写完整的customer.Title_Id,否则框架无法正确匹配模型字段。

2. 模型属性访问路径错误

视图中不能直接读取titles,需要通过控制器传入的模型实例Model访问对应属性,修改为Model.titles。

3. 额外排查项

  • 确认控制器返回视图时,已经为CustomerDetailsViewModel的titles属性完成赋值,未被设为null
  • 确认Lookups类存在PK_Id和Description两个公共属性,拼写、大小写完全匹配你传入SelectList的参数

修正后的控件代码

<div class="form-group">
    <label asp-for="customer.Title_Id" class="col-sm-2 col-md-4 col-form-label">Title</label>
    <select asp-for="customer.Title_Id" asp-items="@(new SelectList(Model.titles,"PK_Id","Description"))"></select>
</div>

可选优化

你可以在ViewModel定义时给列表属性设置默认空值,避免未赋值时抛出空引用异常:

public class CustomerDetailsViewModel
{
    public Customer customer { get; set; }    
    public IEnumerable<Lookups> titles { get; set; } = Enumerable.Empty<Lookups>();
    public List<Lookups> ePCs { get; set; } = new List<Lookups>();
    public List<Lookups> jobStages { get; set; } = new List<Lookups>();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 11:45:07