How to handle MVC DisplayTemplates for two classes with the same name (different namespaces)

Viewed 473

You can only have one View per class name in the DisplayTemplates folder as the class name is used as the name of the view.cshtml file.

However, you can have two classes in a solution with the same name if they appear in different namespaces:

MyNamespace.Class1
MyOtherNamespace.Class1

Both try to use the DisplayTemplate defined by view:

Class1.cshtml

However in the view file you must declare the model - for example:

@model MyNamespace.Class1

This means that if you have a DisplayFor which takes a MyOtherNamespace.Class1 you get a runtime error due to a type mismatch.

If you knew in advance the places where this was going to happen you could use the UIHint to force the DisplayFor to use an alternative template (or you could use a named template directly in the view). But if you don't know in advance (you have all these objects in an enumeration of some kind and therefore can't write specific code to handle edge cases like this without a lot of unwieldy reflection - is there any way to have DisplayTemplates for these classes?

1 Answers
Related