ASP.NET MVC 3 Common DisplayTemplates

I just started a project using ASP.NET MVC 3. I build on top of an existing object system, so one of the first things I have to do is define the display and editor templates for the various types that exist.

Is it possible in MVC to define a DisplayTemplate with a common argument? For example, we have a BitString<T> class that takes an enumeration as a general argument and presents a list of options that wrap the provided enumeration. I hope I can define one Display / Editor template that handles all instances of BitString.

I'm currently using Razor for my views, but I don't mind mixing and matching with ascx (or direct C # if there is a way to do this) to achieve this.

thanks

EDIT: I think this might be a fool of this question ... But it's a year and a half, so maybe someone has the best answer at the moment? General partial view: how to set a general class as a model?

+6
generics c # asp.net-mvc-3
source share
4 answers

The problem you are describing is the fundamental principle of generics.

ICollection<Object> not the base class of ICollection<String> , even if String is a child of the Object class. This is done at compile time, so you basically get two different definitions of the ICollection class. Therefore, they cannot be cast. (SO smart people, please feel free to correct me for any inaccuracies)

In MVC3, I worked on this by doing the following:

 class Container{ /* Stuff here */ } class Container<T> : Container{ T Data {get;set;} } 

Then in your opinion

 @model Container 

If you need only ordinary material, not knowing the general type.

 @model Container<SomeDataType> 

If you need data of type type.

Use Case:

I am creating a ModelContainer class that stores my model internally, along with an array of error messages that may render the page in partial. Since the partial part can be used on every page, it does not know what the Generic type will be, so this workaround is necessary.

This cannot be used if you are trying to access shared data without knowing its type. Hope this solves your problem.

+7
source share

I agree with Daril's answer, but I would just add a slight improvement.

 interface IContainer{ dynamic Data {get;} } class Container<T> : IContainer{ T Data {get;set;} dynamic IContainer.Data { get { return this.Data; } } } 

Then in your view do the following:

 @model IContainer 
+5
source share

No, it is impossible to have representations with a common type if this common type is unknown. You cannot define a model like this:

 @model AppName.Models.BitString<T> 

T should be known:

 @model AppName.Models.BitString<SomeEnum> 

Speaking of which, I recommend you, instead of reusing some models that you had in your old system, to think about which models to view you can install and which will be passed to the views.

+4
source share

It may be less than ideal, but you should be able to use

 @model BitString<dynamic> 
0
source share

All Articles