tags:

views:

836

answers:

3

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!

+3  A: 

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"]) %>
georg
A: 

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
       }
   }
%>
veggerby
+1  A: 

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...

zsharp