如何在显示MVC视图对象的列表? [英] How to Displaying a list of objects in MVC View?

查看:264
本文介绍了如何在显示MVC视图对象的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回字符串的列表的方法。我只是想在视图中显示为纯文本列表

I have a method that is returning a list of strings. I simply would like to display that list in the view as plain text.

这里是从控制器名单:

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循环,并使用引用列表@ 但如何?

I figure i must do something in the view like a foreach loop and and reference the list using "@" but how?

推荐答案

您应该在你的控制器首先返回查看和更改服务()的类型为List

You should return a view in your controller first and change the type of Service() to List

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());
}

这引用您的视图模型后:

After this reference the model in your View:

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

在我的例子中的ActionResult看起来是这样的:

In my example the ActionResult looks like this:

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);
}



这就造成了输出:

Which resulted in the output:

这篇关于如何在显示MVC视图对象的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆