How to display a list of objects in an MVC View?

后端 未结 2 1568
攒了一身酷
攒了一身酷 2021-01-13 07:17

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.

Here\'s the list from the controller:<

2条回答
  •  花落未央
    2021-01-13 08:22

    Your action method Service should return a View. After this change the return type of your Service() method from string to 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());
    }
    

    After this reference the model in your View:

    @model List
    @foreach (var element in Model)
    {
        

    @Html.DisplayFor(m => element)

    }

    In my example the ActionResult looks like this:

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

    Which resulted in the output:

    enter image description here

提交回复
热议问题