How to create a view from the general list?

I have a generic List <T> and I want to create a view that iterates through the list and produces output.

I come up with a couple of problems:

  • I do not know how to get my view.aspx to understand T
  • I do not know how to make it do the right partial for T

For example, if I go to the CustomObject1 list, then I want to display a partial CustomObject1.ascx, and if I go to the CustomObject2 list, I want to display a partial CustomObject2.ascx.

Is there an easy way to do this that I missed? I don’t want to have another aspx variable for every type of list I want to use, I just generate the elements after all. So it is a waste to have 15 different views to cover every type of list that I will need to use.

Any ideas or solutions would be greatly appreciated.

+3
source share
3 answers

If your names will always match (CustomObject1, then I want to display a partial CustomObject1.ascx), you can use a type name. So:

void MyMethod(List<T> items)
{
    foreach(T item in items)
    {
        Html.RenderPartial(item.GetType().Name, item);
    }
}
+2
source

An example of Anthony's first answer: make the contents of the list responsible for rendering itself, for example,

interface IHtmlRenderable
{
    void RenderHtml();
}

void MyMethod(List<T> items) //where T implements IHtmlRenderable
{
    foreach(T item in items) ((IHtmlRenderable)item).RenderHtml();
}

, - ..

+2

, , CustomObjects. List<IMyCommonInterface>.

ascx, , .

, .

  • ICommonInterface , . , - .
  • , CustomObject, , . , , , - .
+1

Source: https://habr.com/ru/post/1719789/


All Articles