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

如何检查ViewBag.Funds中是否包含指定字符串?

问题:检查ViewBag.Funds是否包含指定字符串

控制器代码如下:

string[] checkedBoxes;
ViewBag.Funds = checkedBoxes;

其中checkedBoxes是视图页面表单提交的字符串数组。需要在视图中检查ViewBag.Funds是否包含指定字符串,尝试使用以下代码时出现错误:

@if (ViewBag.Funds.ContainsKey("a"))
{
               
}

报错信息:RuntimeBinderException: 'System.Array' does not contain a definition for 'ContainsKey',即使引入@using System.Linq后使用.Contains()方法也无法正常工作。


解决方法

错误原因

  • ContainsKey是字典(Dictionary)类的专属方法,而ViewBag.Funds是字符串数组,数组不存在该方法,直接调用必然报错。
  • ViewBag属于动态类型(dynamic),编译器无法自动识别Linq的扩展方法Contains,必须先明确其具体类型才能调用该方法。

正确实现步骤

  1. 确保视图顶部引入Linq命名空间:
    @using System.Linq
    
  2. 将ViewBag.Funds强制转换为string[]类型,再调用Contains方法,同时处理null情况避免空引用异常:
    @if (((string[])ViewBag.Funds)?.Contains("a") == true)
    {
        // 此处编写你的业务逻辑
    }
    
    也可以先判断非null再执行检查:
    @if (ViewBag.Funds != null && ((string[])ViewBag.Funds).Contains("a"))
    {
        // 此处编写你的业务逻辑
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:02:15