ASP.net MVC - 渲染包含不同类型的列表,以及每种类型有不同的看法 [英] ASP.net MVC - rendering a List containing different types, with a different view for each type
问题描述
想象我有实现所谓的接口对象的列表ISummary
该列表中的对象可以有附加属性IE浏览器。
Imagine I have a list of objects that implement an interface called ISummary The objects within this list MAY have additional properties ie.
public interface ISummary {
Guid Id {get;set;}
string Title {get;set;}
DateTime Created {get;set;}
}
public class GigSummary: ISummary {
Guid Id {get;set;}
string Title {get;set;}
DateTime Created {get;set;}
string VenueName {get;set}
string Band {get;set;}
}
public class NewsSummary: ISummary {
Guid Id {get;set;}
string Title {get;set;}
DateTime Created {get;set;}
string Author{get;set}
}
我现在通过演出和新闻摘要对象名单(截至ISummary列表)的视图模型。
I now pass this list of Gigs and News Summary objects (as a list of ISummary) to the view as the model.
我想用一个不同的部分为包含在列表中的每个类型来呈现这个列表。
I want to render this list using a different partial for each type contained in the list.
我怎样才能做到这一点是ASP.NET MVC?
How can I do this is ASP.NET MVC?
推荐答案
我能想到的最明显的方法是做这样的事情:
The most obvious way I can think of would be to do something like:
foreach(ISummary summ in listOfISummary) {
Html.RenderPartial(String.Fomat("~/Views/Shared/{0}Renderer.ascx", summ.GetType.ToString()), summ, ViewData);%>
}
和创建一个命名约定,如NewsSummaryRenderer.ascx一个强类型的视图。
and create a strongly typed view with a naming convention, like NewsSummaryRenderer.ascx.
我希望你能移动,虽然这出一个辅助方法,但我会通过扩展方法将其添加到现有的一个助手,而不是把它在一个code后面的建议previously
I expect that you could move this out to a helper method though, but I'd add it to one of the existing helpers through an extension method rather than putting it in a code behind as suggested previously.
这篇关于ASP.net MVC - 渲染包含不同类型的列表,以及每种类型有不同的看法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!