Asp.Net MVC - Strongly Typed View with Two Lists of Same Type

做~自己de王妃 提交于 2019-12-07 05:42:24

问题


I have a View strongly typed to an Item class. In my controller I need to send two different List. Is there an easier way to do this other than creating a new class with two List.

What I am ultimately trying to do is have on my homepage 10 items ordered by Date, and 10 items ordered by Popularity.

WHAT I DID

I actually went with a combination of the two answers. I strongly-typed my View to the new class I created with the two lists. I then strongly-typed two partial views to the each one of the lists. May seem like overkill, but I like how it turned out.


回答1:


"creating a new class with two Lists" is the way to go. It's called a view model and once you embrace it, the power of strongly-typed views really opens up. It can be this simple:

public class IndexViewModel 
{
    public List<Item> Newest { get; set; }
    public List<Item> Popular { get; set; }
}



回答2:


There are two general philosophies to this. The first is to take the approach John Sheehan stanted. You create a custom view model with both lists and pass that to your strongly typed view.

The second is to consider the lists as "ancillary" data and put them in ViewData like jeef3 stated. But, when you render the lists, you use a strongly typed partial.

ViewData["Newest"] = Newest;
ViewData["Popular"] = Popular

By that I mean in your main view, you'd call RenderPartial(...) but pass in the view data key you used.

And your partial would look like:

<%@ ViewUserControl Inherits="System.Web.Mvc.ViewUserControl<List<Item>>" %>
...

This gives you strongly typed access to that view data from within your partial.




回答3:


It's what John suggested or not having a strongly typed view and adding them to the ViewData:

ViewData["Newest"] = Newest;
ViewData["Popular"] = Popular

Another option would be Strongly Typed Partial views.




回答4:


You should make a model that includes both lists specifically for the view.

Typically in the little MVC I have done, I have made a model for each view even if they just passed along identically data that was served up for by data or business layer just to keep the separation between the two parts very strict. This setup is a little more work and not needed in many simple cases but it does keep things cleaner in my opinion.



来源:https://stackoverflow.com/questions/1275700/asp-net-mvc-strongly-typed-view-with-two-lists-of-same-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!