Home > OS >  How to show 2 lists in ASP.NET MVC view
How to show 2 lists in ASP.NET MVC view

Time:12-14

I am sending File and and file path that are both List from controller to the ASP.NET MVC view:

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

return View();

and this is how show it in the 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 />
}

This is the output I am expecting:

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

Getting this error:

Value cannot be null. Parameter name: source

on this line:

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

CodePudding user response:

There might be a filtration issue as you are using x.Contains(item) which will fail for string with difference case (uppercase/lowercase). Try following code :

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

If above solution does not works then there is problem with the statement ViewBag.releaseNoteFiles as string[]. Confirm the value in ViewBag.releaseNoteFiles, whether it can be casted into string[]

CodePudding user response:

IMHO your releaseNoteFiles are not array and it gives a null exception. ViewData requires type casting for complex data types but ViewBag doesn’t. And to be on a safe side use ToLower to make a case insensitive comparison. So try just this

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