【问题标题】:How to show 2 lists in ASP.NET MVC view如何在 ASP.NET MVC 视图中显示 2 个列表
【发布时间】:2022-01-16 15:47:30
【问题描述】:

我正在将文件和文件路径从控制器发送到 ASP.NET MVC 视图:

.....
ViewBag.releaseNoteFilesmonth = month; // this has list of months
ViewBag.releaseNoteFiles = releaseNoteFiles; //this has list of the path to the files

return View();

这是在视图中显示的方式:

@foreach (var item in ViewBag.releaseNoteFilesmonth)
{
    string url = (ViewBag.releaseNoteFiles as string[]).Where(x => x.Contains(item)).FirstOrDefault();
    <a href="@url"> @item</a>
    <br />
}

这是我期待的输出:

OCT - (Link to the file)
NOV - (Link to the file)
Dec - (Link to the file)

收到此错误:

值不能为空。参数名称:来源

在这一行:

string url = (ViewBag.releaseNoteFiles as string[]).Where(x => x.Contains(item)).FirstOrDefault();

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    在您使用x.Contains(item) 时可能存在过滤问题,这对于具有不同大小写(大写/小写)的字符串将失败。 试试下面的代码:

    x.ToLower().Contains(item.ToLower())
    

    如果上述解决方案不起作用,则声明 ViewBag.releaseNoteFiles as string[] 存在问题。确认ViewBag.releaseNoteFiles中的值,是否可以转换成string[]

    【讨论】:

      【解决方案2】:

      恕我直言,您的 releaseNoteFiles 不是数组,它给出了一个空异常。 ViewData 需要对复杂数据类型进行类型转换,但 ViewBag 不需要。为了安全起见,使用 ToLower 进行不区分大小写的比较。所以试试这个

       string url = ViewBag.releaseNoteFiles.Where(x=x.ToLower().Contains(item.ToLower()))
      .FirstOrDefault();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-21
        • 2015-05-11
        • 1970-01-01
        相关资源
        最近更新 更多