简体   繁体   中英

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.

    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. 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. But I beleieve it makes more sense to wrap the lists in a single object model which you then pass to the 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).

public class Action 
{

    //...

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

    //...
}

Nothing special MVC'ish here...

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
       }
   }
%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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