ASP.NET Core MVC视图传模型报ViewDataDictionary类型不匹配异常

上图是需要在视图中实现的效果。
异常原因
页面抛出的类型不匹配异常信息如下:
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'ExposureTracker.Models.Accumulation', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.List`1[ExposureTracker.Models.Accumulation]
核心问题是视图和控制器传参的模型类型不一致:
- 视图顶部声明的强类型模型是
IEnumerable<Accumulation>,也就是Accumulation对象的集合 - 控制器
ViewDetails方法中传入视图的是单个Accumulation实体对象,不是集合,因此触发异常。
解决方案
从现有代码逻辑看,你是在循环中把所有BASIC类型的保额、再保风险净值累加到同一个Accumulation实例中,最终只会生成1条汇总数据,不需要强制转换为ToList(),两种修复方式二选一即可:
方案1:修改视图模型类型(适配现有汇总逻辑,推荐)
直接把视图的模型声明改为单个Accumulation类型,去掉遍历逻辑,直接绑定模型属性即可:
@model ExposureTracker.Models.Accumulation <div class="table-responsive-md mb-1 mt-5"> <table class="table table-striped table-hover table-bordered" id="basic-datatables" cellspacing="0"> <thead class="bg-dark text-light"> <tr> <th>Insured Prod</th> <th>Sum Assured/Face Amount</th> <th>Reinsured Net Amount At Risk</th> </tr> </thead> <tbody> <tr> <td>@Model.insuredprod</td> <td>@Model.basictotalsumassured</td> <td>@Model.basictotalreinsuredamount</td> </tr> </tbody> </table> </div>
控制器原有返回逻辑不需要调整,即可正常运行。
方案2:控制器返回集合类型模型
如果后续需要扩展展示多条Accumulation记录,就把控制器中生成的单个Accumulation实例包装为列表再传入视图,修改ViewDetails方法的返回代码:
// 原返回代码:return View("ViewAccumulation", ListAccumulation); // 替换为以下代码 var accumulationList = new List<Accumulation> { ListAccumulation }; return View("ViewAccumulation", accumulationList);
这种方案不需要修改现有视图代码,但和当前单条汇总的业务逻辑匹配度低,非必要不选。
额外注意:现有代码中无参数的
ViewAccumulation动作方法直接返回视图没有传模型,直接访问该接口会因为模型为空抛出异常,如果该入口需要使用,记得传入对应类型的模型实例。
内容的提问来源于stack exchange,提问作者Veck

