我將檔案和檔案路徑都從控制器發送到 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();
uj5u.com熱心網友回復:
您使用時可能存在過濾問題,x.Contains(item)對于不同大小寫(大寫/小寫)的字串將失敗。嘗試以下代碼:
x.ToLower().Contains(item.ToLower())
如果上述解決方案不起作用,則陳述句有問題ViewBag.releaseNoteFiles as string[]。確認中的值ViewBag.releaseNoteFiles,是否可以轉換成string[]
uj5u.com熱心網友回復:
恕我直言,你的 releaseNoteFiles 不是陣列,它給出了一個空例外。ViewData 需要對復雜資料型別進行型別轉換,但 ViewBag 不需要。為了安全起見,使用 ToLower 進行不區分大小寫的比較。所以試試這個
string url = ViewBag.releaseNoteFiles.Where(x=x.ToLower().Contains(item.ToLower()))
.FirstOrDefault();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/380093.html
標籤:C# asp.net-mvc
