Reputation: 12988
I have a model class like this:
public class GenericModel<T> where T : BaseTest
{
//Ctor
public List<T> TestList{get;set;}
}
I can work ok with this becouse I set it in my controllers and my views. But i have a Partial View wich can be used by all controllers.
I would like to know if i can do somethinf like this in that partial view:
@model GenericModel<T>
Without specifing the generic type. What can i do here? Use an interface or something?
Upvotes: 3
Views: 3879
Reputation: 31097
It's not possible to define it with T
, because it needs an actual type to follow the @model
statement.
In my experience, using refactor in visual studio, extract an interface for GenericModel
say IGenericModel
and for BaseTest
, say IBaseTest
, then your model statements becomes:
@model IGenericModel<IBaseTest>
update:
Just to clarify, the interfaces to extract could be something like (note the out
for variance, it will make your life easier if you use it):
public interface IGenericModel<out T> where T : IBaseTest
{
IEnumerable<T> GetAll(); // just as an example
}
public interface IBaseTest
{
T Property { get; }
}
Upvotes: 2
Reputation: 7034
One possible solution I've used many times is to create a non-generic base-class for your Generic, making it:
public class GenericModel<T> : NormalModel where T:BaseTest
{
}
Your base class could be something like:
public abstract class NormalModel
{
public abstract IList ItemsList { get; }
}
(If it's this simple you'd probably just make it an interface, but I'm assuming there's more to it and some of the GenericModel is not dependent on T and might go in the base class).
Then your view can use the NormalModel
and you'll just have to override it in your GenericModel
and provide it with your TestList
(and anything else that you need to use in your view).
Upvotes: 1