简体   繁体   中英

Model binding for nested inherited objects .Net core

Is it possible to create custom model binder for nested inherited objects? I saw this article https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-5.0 , but my case is more difficult, my objects are very complex.

For example, I have this simple structure:

First level

public class Top
{
    public string Value { set; get; }

    public IEnumerable<MiddleBase> MiddleClasses { set; get; }
}

Second level

public abstract class MiddleBase
{
    public ConcreteMiddleType Type { set; get; }

    public IEnumerable<BottomBase> BottomClasses { set; get; }
}

public class ConcreteMiddle1 : MiddleBase
{
    public string Value1 { set; get; }
}

public class ConcreteMiddle2 : MiddleBase
{
    public string Value2 { set; get; }
}

Third Level

public abstract class BottomBase
{
    public ConcreteBottomType Type { set; get; }
}

public class ConcreteBottom1 : BottomBase
{
    public string Value1 { set; get; }
}

public class ConcreteBottom2 : BottomBase
{
    public string Value2 { set; get; }
}

if I handle request I get error, I can't bind base abstract class.

Did anybody have experience with such issue?

If you really want your base classes to be abstract, you can create a custom ModelBinder and override how the base is handled using bindingContext.MetaData. Here's an example:

MVC 3 Model Binding a Sub Type (Abstract Class or Interface)

Edit: In .net core, the model binder will need to extend IModelBinder interface and a custom IModelBinderProvider will need to be registered when configuring service on startup. The IModelBinderProvider will check for your model type and pass your IModelBinder in its GetBinder function. From your custom IModelBinder, you can access the bindingContext, which has everything you need to deserialize the abstract members of the view model.

Replacing DefaultModelBinder in ASP.net MVC core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM