Abdul Ahmad
Abdul Ahmad

Reputation: 10021

using generics for view model

I have a view that I'd like to give a model to, but the model can be a possible of 2 types. Example:

public class Super {
  public string Name = "super";
}
public class Sub1 : Super {
  public string Name = "sub1";
}
public class sub2 : Super {
  public string Name = "sub2";
}

I'm trying to experiment with generics, and looking at some other questions I see I can do the following, however, am I declaring the variable inside the class correctly?

public class Generic<T> where T : Super {
  public T SubClass { get; set; } //is this ok?
}

if this is ok, how would I add such a class as the model to a view?

@model Generic<??>
<div>@Model.SubClass.Name</div>

is this even feasible, am I on the right track, or am I just kind of doing a whole bunch of nothing?

Upvotes: 0

Views: 72

Answers (2)

Alexei Levenkov
Alexei Levenkov

Reputation: 100610

Razor views don't support generic models - you can have specific generic like IEnumerable<int>, but you can't have IEnumerable<T>.

It looks like you really want regular inheritance with virtual methods and not generics.

public class Super {
  public virtual string Name {get {return "super";}}
}
public class Sub1 : Super {
  override public string Name {get {return "sub1";}}
}

And simply use Super as type of model

@model Super
<div>@Model.Name</div>

Additional note: generic classes have no inheritance relation to each other (Generic<Super> is not in any shape of form related to Generic<Sub1>) - so you can't specify "base" generic class and have it reasonable work for derived classes. Following model will not even allow to pass Generic<Sub1> (you may handle that with interface - read on "generics and covariance")

@model Generic<Super> @* can't pass instance of Generic<Sub1> *@

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239440

Just have your view use Super as the model:

@model Super

You'll be able to pass either Sub1 or Sub2 in since they both inherit from Super.

Upvotes: 3

Related Questions