![](/img/trans.png)
[英]Scripts.Render in c# class (creating html helper). Using functions from HtmlHelper in c# file
[英]Display Each Element From Array Using HTML Helper in C#
這可能是一個非常簡單的問題,但我是 C# / MVC 的新手,我已經收到一個損壞的項目來修復。 所以是時候沉沒或游泳了!
我有一個字符串數組,從 function 傳遞到前端。 該陣列看起來像
reports = Directory.GetFiles(@"~\Reports\");
在前端,我希望它顯示每個報告,但我不知道該怎么做。 這個項目使用的是 MVC,我相信這個視圖叫做“Razor View”? 我知道它正在使用 HTML 助手。
本質上,我需要類似的東西
@HTML.DisplayTextFor(Model.report [And then print every report in the array]);
我希望這是有道理的。
如果你想顯示文件名數組,你可以簡單地使用一個 foreach:
@foreach(var report in Model.Reports){ @report }
請注意,您應該將 Reports 屬性添加到您的視圖 model:
public class SampleViewModel
{
public string [] Reports { get; set; }
}
您可以使用 ViewData 或 TempData,但我發現使用視圖 model 是更好的方法。
然后您可以填充它:
[HttpGet]
public ActionResult Index()
{
var model = new SampleViewModel(){ Reports = Directory.GetFiles(@"~\Reports\")};
return View(model);
}
並在您認為合適的視圖中使用它。
這里有一個簡單的在線例子: https://do.netfiddle.net/5WmX5M
如果您想在視圖級別添加 null 支票,您可以:
@if(Model.Reports != null)
{
foreach(var report in Model.Reports){ @report <br> }
}
else
{
<span> No files found </span>
}
https://do.netfiddle.net/melMLW
這絕不是一個壞主意,盡管在這種情況下,如果找不到文件, GetFiles
將返回一個空列表,並且我假設正在處理可能的 IOException。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.