Asp.net Core调用GetProperty传ViewBag参数报RuntimeBinderException问题
问题原因
- 核心错误是
ViewBag是dynamic动态类型,Type.GetProperty()方法要求传入string类型的参数,直接传动态类型参数时,运行时绑定无法匹配到正确的方法重载,所以抛出RuntimeBinderException。 - 另外你的代码存在两处逻辑错误:
- 默认排序分支连续两次给
ViewBag.SortField赋值,第二次直接把枚举值SortDirection.Ascending赋给了ViewBag.SortField,直接把排序字段覆盖成了枚举值,就算做类型转换也会获取不到属性。 - 非默认排序的
else分支缺少大括号,只有第一行逻辑受else控制,ViewBag.SortField = sortField会无条件执行。
- 默认排序分支连续两次给
解决方案
方案1:强制转换动态类型参数(快速修复)
把用到ViewBag值的地方都转成对应类型,同时修复逻辑错误即可:
private List<Employee> SortEmployees(List<Employee> employees, String sortField, string currentSortField, SortDirection sortDirection) { if (string.IsNullOrEmpty(sortField)) { ViewBag.SortField = "EmployeeNumber"; // 修复笔误:给SortDirection赋值而非覆盖SortField ViewBag.SortDirection = SortDirection.Ascending; } else { // 补全大括号避免逻辑错误 if (currentSortField == sortField) { ViewBag.SortDirection = sortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending; } else { ViewBag.SortDirection = SortDirection.Ascending; } ViewBag.SortField = sortField; } // 将dynamic类型的ViewBag.SortField强制转成string传入 var propertyInfo = typeof(Employee).GetProperty((string)ViewBag.SortField); // 排序方向判断也做强制转换 if ((SortDirection)ViewBag.SortDirection == SortDirection.Ascending) { employees = employees.OrderBy(e => propertyInfo.GetValue(e, null)).ToList(); } else { employees = employees.OrderByDescending(e => propertyInfo.GetValue(e, null)).ToList(); } return employees; }
方案2:直接用方法入参处理排序(更推荐)
SortEmployees方法本身已经传入了强类型的sortField和sortDirection参数,排序逻辑完全可以直接用这两个参数,不需要依赖动态类型的ViewBag,从根源避免动态类型绑定错误,同时增加空校验兼容非法字段输入:
private List<Employee> SortEmployees(List<Employee> employees, string sortField, string currentSortField, SortDirection sortDirection) { // 用局部强类型变量存储排序规则,避免依赖dynamic string finalSortField = nameof(Employee.EmployeeNumber); SortDirection finalSortDir = SortDirection.Ascending; if (!string.IsNullOrEmpty(sortField)) { finalSortField = sortField; finalSortDir = currentSortField == sortField ? (sortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending) : SortDirection.Ascending; } // ViewBag只负责给视图传值,不参与业务逻辑计算 ViewBag.SortField = finalSortField; ViewBag.SortDirection = finalSortDir; // 直接用强类型变量获取属性,加空校验避免非法字段报错 var propertyInfo = typeof(Employee).GetProperty(finalSortField) ?? typeof(Employee).GetProperty(nameof(Employee.EmployeeNumber)); employees = finalSortDir == SortDirection.Ascending ? employees.OrderBy(e => propertyInfo.GetValue(e, null)).ToList() : employees.OrderByDescending(e => propertyInfo.GetValue(e, null)).ToList(); return employees; }
内容的提问来源于stack exchange,提问作者ha33
相关产品推荐
相关产品推荐

