如何在MVC视图中显示对象列表?
我有一个返回字符串列表的方法。 我只想在视图中以纯文本forms显示该列表。
这是控制器的列表:
public class ServiceController : Controller { public string Service() { //Some code.......... List Dates = new List(); foreach (var row in d.Rows) { Dates.Add(row[0]); } return Dates.ToString(); } public ActionResult Service() { Service(); } }
并且观点:
HEJ @Html.Action("Service", "Service")
我想我必须在视图中做一些像foreach循环一样的东西,并使用“@”引用列表,但是如何?
您的操作方法Service
应返回View
。 在此之后,将Service()方法的返回类型从string
更改为List
public List Service() { //Some code.......... List Dates = new List (); foreach (var row in d.Rows) { Dates.Add(row[0]); } return Dates; } public ActionResult GAStatistics() { return View(Service()); }
在此之后参考视图中的模型:
@model List @foreach (var element in Model) { @Html.DisplayFor(m => element)
}
在我的例子中,ActionResult看起来像这样:
public ActionResult List() { List Dates = new List (); for (int i = 0; i < 20; i++) { Dates.Add(String.Format("String{0}", i)); } return View(Dates); }
这导致了输出:
您可以在视图中执行以下操作,
@foreach (var item in @Model) { @item.PropertName }