ASP.net MVC - rendering a List containing different types, with a different view for each type

后端 未结 5 1054
清歌不尽
清歌不尽 2020-12-29 00:29

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         


        
5条回答
  •  佛祖请我去吃肉
    2020-12-29 00:44

    Here's a simple extension method you can create to extract just the types you need:

    public static class Extensions
    {
        public static IEnumerable ExtractOfType(this IEnumerable list)
            where T : class
            where U : class
        {
            foreach (var item in list)
            {
                if (typeof(U).IsAssignableFrom(item.GetType()))
                {
                    yield return item as U;
                }
            }
        }
    }
    

    Test:

    public interface IBaseInterface
    {
        string Foo { get; }
    }
    
    public interface IChildInterface : IBaseInterface
    {
        string Foo2 { get; }
    }
    
    public interface IOtherChildIntreface : IBaseInterface
    {
        string OtherFoo { get; }
    }
    
    public class BaseImplementation : IBaseInterface
    {
        public string Foo { get { return "Foo"; } }
    }
    
    public class ChildImplementation : IChildInterface
    {
        public string Foo2 { get { return "Foo2"; } }
        public string Foo { get { return "Foo"; } }
    }
    
    public class OtherChildImplementation : IOtherChildIntreface
    {
        public string OtherFoo { get { return "OtherFoo"; } }
        public string Foo { get { return "Foo"; } }
    }
    

    ....

            List b = new List();
            b.Add(new BaseImplementation());
            b.Add(new ChildImplementation());
            b.Add(new OtherChildImplementation());
            b.Add(new OtherChildImplementation());
    
    
            foreach (var s in b.ExtractOfType())
            {
                Console.WriteLine(s.GetType().Name);
            }
    

    This will get all of the items in the list that are of the derived type you're looking for. So, in your controller, pass in the entire list to the view. Then, have partial views that take IEnumerable's of the type that partial needs, and within your main view, call this extension method and pass on the result to those individual partial views.

提交回复
热议问题