开发者

ASP.NET MVC3 ForEach on Two Different Data Structures

I understand how to handle a foreach loop over a single data structure using page inheritance in ASP.NET MVC, but I want to display the contents of two different t开发者_开发知识库ypes of data on the same page. How can this be done since pages only accept one class for inheritance?


As the guys before me pointed out, the correct answer if we understood you correctly is composition. The idea is to give the page one model, which contains two other models, eg.

public class Car {
    public Motor Engine { get; set; }
    public List<Seat> Seats { get; set; }
}

The idea here is that your class now derives from ViewPage<Car>, which allows you to do this:

Sitting behing a <%= Model.Engine.ToString() %> engine, there are:

<ul>
<% foreach(var seat in Model.Seats) { %>
       <li><%= seat.ToString() %>
<% } %>
</ul>

Hope this answers your question.


I know of these two choices:

  1. Make a class that contains both subclasses (a view model).
  2. Use ViewData or ViewBag to pass one or more of the instances to the view.


Composition

public class CompositeViewModel
{
    public ViewModelClass1 ViewModel1 { get; set; }
    public ViewModelClass2 ViewModel2 { get; set; }
}


Create a view model class.

class ViewModel 
{
    MyClass1 Object1 { get; set; }
    MyClass2 Object2 { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜