0

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 Answers 3

3

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"]) %>
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

zsharp, how do you wrap them?
or can I use ViewBag for it? I mean ViewBag instead of ViewData
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.