2014-03-12 24 views
5

我有一個方法返回一個字符串列表。我只是想以純文本的形式在視圖中顯示該列表。如何顯示MVC視圖中的對象列表?

這裏是從控制器列表:

public class ServiceController : Controller 
{ 

    public string Service() 
    { 
     //Some code.......... 
     List<string> Dates = new List<string>(); 
     foreach (var row in d.Rows) 
     { 
      Dates.Add(row[0]); 
     } 
     return Dates.ToString(); 
    } 

    public ActionResult Service() 
    { 
     Service(); 
    } 
} 

和視圖:

<table class="adminContent"> 
    <tr> 
     <td>HEJ</td> 
    </tr> 
    <tr> 
     <td>@Html.Action("Service", "Service")</td> 
    </tr> 
    </tr> 
</table> 

我想我必須做的像一個foreach循環的觀點的東西,並引用列表使用「@」但是如何?

+0

您可以檢查這個例子:http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music -store-part-3 –

回答

11

你應該在你的控制器首先返回查看和更改服務的類型()列出

public List<string> Service() 
{ 
    //Some code.......... 
    List<string> Dates = new List<string>(); 
    foreach (var row in d.Rows) 
    { 
     Dates.Add(row[0]); 
    } 
    return Dates; 
} 

public ActionResult GAStatistics() 
{ 
    return View(Service()); 
} 

此引用後在您的視圖模型:

@model List<string> 
@foreach (var element in Model) 
{ 
    <p>@Html.DisplayFor(m => element)</p> 
} 

在我的例子中的ActionResult看起來是這樣的:

public ActionResult List() 
{ 
    List<string> Dates = new List<string>(); 
    for (int i = 0; i < 20; i++) 
    { 
     Dates.Add(String.Format("String{0}", i)); 
    } 
    return View(Dates); 
} 

這就造成了輸出:

enter image description here

+0

其實這樣做很有意義。謝謝! Btw是for循環真的nessesary?我的意思是,讓我們說我們不知道如何在列表中的曼尼項目,我可以做一個foreach循環,而不是最大的結果嗎?或者這個:for(int i = 0; i!= 0; i ++) { Dates.Add(String.Format(「String {0}」,i)); } return View(Dates); – koffe14

+1

控制器中的for循環僅用於演示目的以獲取列表中的某些內容。使用任何你喜歡的和任何你需要的東西。 – Marco

+0

似乎我有問題。我已經有一個模型@model ServiceListModel獲取錯誤,我只能有1個模型。 – koffe14

2

可以作爲視圖下做到這一點,

@foreach (var item in @Model)  
{  
    <li>@item.PropertName</li> 
} 
相關問題