简体   繁体   English

在ASP.NET MVC(C#)中返回多个列表

[英]Returning Multiple Lists in ASP.NET MVC (C#)

I'm somewhat new to the ASP.NET MVC architecture and I'm trying to sort out how I could return multiple sets of data to the view. 我是ASP.NET MVC架构的新手,我试图弄清楚如何将多组数据返回到视图。

    public ActionResult Index(string SortBy)
    {
        var actions = from a in dbActions.Actions
                       orderby a.action_name
                       ascending
                       select a;
        return View(actions.ToList());
    }

This code works very well for returning a single dataset. 此代码对于返回单个数据集非常有效。 The situation I have is a that I've got a list of objects, each of which has a subset of objects that I want to display in a hierarchy on the output page. 我遇到的情况是我有一个对象列表,每个对象都有一个对象子集,我希望在输出页面的层次结构中显示这些对象。 I'm not sure whether I'm looking for the quick way or the right way, thoughts on both avenues would be very much appreciated. 我不确定是要寻找快速的方法还是正确的方法,对这两种途径的想法将不胜感激。

Thanks! 谢谢!

You could pass them through ViewData, an object that is passed from the controller to the view. 您可以通过ViewData(一个从控制器传递到视图的对象)传递它们。 The controller would look like this: 控制器将如下所示:

ViewData["ActionList"] = actions.ToList();

Retrieving it in the view: 在视图中检索它:

<% foreach (var action in (List)ViewData["ActionList"]) %>

ViewData as described above is the quick way. 如上所述的ViewData是快速方法。 But I beleieve it makes more sense to wrap the lists in a single object model which you then pass to the View. 但我相信将列表包装在单个对象模型中更有意义,然后将其传递给View。 You will also get intellisense... 您还将获得智能感知...

That subset of objects could/should be returned by a property on the Action (assuming db.Actions returns Action objects). 对象的子集可以/应该由Action上的属性返回(假设db.Actions返回Action对象)。

public class Action 
{

    //...

    public IEnumerable<SubAction> SubActions 
    {
         get { return do-what-ever; }
    }

    //...
}

Nothing special MVC'ish here... 这里没什么特别的MVC ...

In your view you just loop through both: 在您看来,您只需遍历这两个步骤:

<%
   foreach (Action a in ViewData.Model as IList<Action>) 
   {
       foreach (SubAction sa in a.SubActions)
       {
          // do whatever
       }
   }
%>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM