Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass a generic object to a Aspx page
    text
    copied!<p>I am working on an ASP.Net MVC website and I am stuck on a getting my C# code using generics to play nice with my views.</p> <p>I have a Controller that passes a Model to a View (so far so good). The Model is of type <code>IDescribedEnumerable&lt;T&gt;</code> with some constraints on <code>T</code>, among those is the constraint that <code>T</code> inherits from an interface (<code>IDescribedModel</code>). </p> <p>I can easily write a View that accepts an <code>IDescribedEnumerable&lt;Country&gt;</code> and that will work as long as <code>T</code> is in fact the type <code>Country</code>. </p> <p>However, I'd also like to write a default view that accepts an <code>IDescribedEnumerable</code> of <code>&lt;&lt;whatever&gt;&gt;</code> and that will render it. This should be entirely possible. I don't always need to know the specific type of the Model. Often just knowing that it's an <code>IDescribedModel</code> is enough.</p> <p>As long as I stay in C# there is no problem. When I don't care about the specific type I just declare methods and objects as accepting a <code>&lt;T&gt;</code>. When I do care I declare them as accepting <code>Country</code>.</p> <p>But:<br> (1) If I want to render a View I have to pick an type. I can't just say <code>Inherits="System.Web.Mvc.ViewUserControl&lt;IDescribedEnumerable&lt;T&gt;&gt;"</code> I have to specify an existing type between the <code>&lt;&gt;</code>. (even if I were to inherit from <code>ViewUserControl</code> I'd have to cast it to an <code>IDescribedEnumerable&lt;&lt;something&gt;&gt;</code>. (2) Ideally I'd say that Model is <code>IDescribedEnumerable&lt;IDescribedModel&gt;</code> in the default View and <code>IDescribedEnumerable&lt;Country&gt;</code> in the specific implementation. However, then my Controller needs to know whether he's going to render to the default View or the specific view. It is not possible to simply cast an object that is <code>IDescribedEnumerable&lt;Country&gt;</code> to <code>IDescribedEnumerable&lt;IDescribedModel&gt;</code>. (IIRC it is possible in C# 4, but I'm using 3.5)</p> <p>So what should I do? All options I can think of are very sub-optimal (I'm not looking forward to removing the generics and just casting objects around, nor to copy pasting the default view 65 times and keeping the copies synchoronized, nor going reflection gallore and creating an object based on a known <code>Type</code> object)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload