开发者

ASP.NET MVC2 - Model Binding multiple data sources on one View page - Options?

开发者 https://www.devze.com 2023-02-12 18:10 出处:网络
I have one view page (MyView.aspx) and many data sources to bind on this page. Lets say it has Books, Publishers, Comments, etc.

I have one view page (MyView.aspx) and many data sources to bind on this page.

Lets say it has Books, Publishers, Comments, etc.

Each one of those has an object which provides a List, List, etc.

In my view, what are my optiosn for multilple model biding?

I want to check to see if each one is empty, and then enumerate it. But I can't check Model.Count() because wouldn't Model be made of all those objects if I set the page to开发者_StackOverflow中文版 inheriet from ?

What are my options? Should I load each content area in a control/partial view?

Or can I just dump each object into ViewData and then check the count by casting in the view?

Thanks so much for taking a look at my problem.


Have you considered using a ViewModel that contains all Lists of all of your different data fields and using that to populate your View?

Example:

ViewModel:

public class MyViewModel
{
   List<Book> Books {get; set;}
   List<Publisher> Publishers {get; set;}
   List<Comment> Comments {get; set;}
   //Other fields...

   //Constructors...
}

Then in your View you could simply check if a specific field was null prior to enumerating through it:

View:

if(Model.Books.Count() != 0)
{
   //Enumerate through results here
}


Rionmonster's is probably the best solution - another is to use strongly typed partial views. You could load everything into the view data and then inject each segment into the respective partial view.

0

精彩评论

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

关注公众号