user-interface.net-coreinheritanceabstract-classeditorfor

EditorFor for derived classes when passing it packed as Abstract class


I have many classes that inherit from an abstract class.

I'm trying to make @Html.EditorFor to choose correct editor when we pass an class packed up in abstract class which is inherited from to it.

First look for a file in EditorTemplates that accepts this class wrapped in an abstract class, and if it doesn't find it, it will take the editor by the name of the abstract class.

In .NET Framework it work for me out of the box but in Core it doesnt...

For example:

public class Box
{
    AbstractClass AC { get; set; }
}

public abstract class AbstractClass 
{ 

}

public class NonAbstractClass1 : AbstractClass
{

}

public class NonAbstractClass2 : AbstractClass
{

}

And we have cshtmls:

AbstractClass.cshtml:

@model AbstractClass

<div>AbstractClass</div>

NonAbstractClass1.cshtml:

@model NonAbstractClass1

<div>NonAbstractClass1</div>

NonAbstractClass2.cshtml:

@model NonAbstractClass2

<div>NonAbstractClass2</div>

Box.cshtml:

@model Box

@Html.EditorFor(x => x.AC)

If Model in Box is NonAbstractClass2 packed in AbstractClass I want it to use NonAbstractClass2.cshtml if its AbstractClass I want AbstractClass.cshtml etc...

Any hints bois?


Solution

  • Got an answer.

    @Html.EditorFor(x => x.AC, Model.AC.GetType().Name)
    

    I think I've tried this before and it throwed me an exception of type but now it works lol.