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

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

问题描述

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

I have a method that is returning a list of strings. I simply would like to display that list in a 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?

推荐答案

您的操作方法Service应该返回View.在此之后,将Service()方法的返回类型从string更改为List<string>

Your action method Service should return a View. After this change the return type of your Service() method from string to List<string>

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

输出结果:

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

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