1

What is the easiest way to use inheritance in action using ASP.NET CORE MVC?

For example, I have 3 classes:

public class Common
{
  public string CommonField { get; set; }
}

public class A : Common
{      
  public string FieldA { get; set; }
}

public class B : Common
{
  public string FieldB { get; set; }
}

I have controller action

IActionResult Post([FromBody] [ModelBinder(BinderType = typeof(MyCustomeBinder))] Common field)
{
  //process field here
}

what is the best way to replace field initialization(based on some query parameter (for example, type=a)) in action before binding? I still need all properties to be filled from body.

I already have something like:

public class MyCustomBinder : IModelBinder
{
  public Task BindModelAsync(ModelBindingContext bindingContext)
  {
    switch (bindingContext.HttpContext.Request.Headers["type"])
            {
                case "a":
                    bindingContext.Result = ModelBindingResult.Success(new A());
                    break;
                case "b":
                    bindingContext.Result = ModelBindingResult.Success(new B());
                    break;
                default:
            }

                return TaskCache.CompletedTask;
  }
}

It's correct object coming to action, but all fields are empty.

tereško
  • 58,060
  • 25
  • 98
  • 150
inser
  • 1,190
  • 8
  • 17
  • I know I can create custom `CustomModelBinder : IModelBinder`, but how can I use default value provider then to fill my fields from body? – inser Nov 03 '17 at 09:13
  • You can't. You either have to make your own model binder, or use different methods and action names. – Patrick Hofman Nov 03 '17 at 09:15
  • Yes, I need to create my own model binder. But how can I fill then it properties using SimpleTypeModelBinder? In fact my goal is to replace `field` property with proxy object before initialization using Castle.Proxies. I don't think it's duplicate question – inser Nov 03 '17 at 09:20
  • @PatrickHofman why do you think it's duplicate? I think there are 2 different questions. – inser Nov 03 '17 at 09:39
  • For to questions you actually have to ask two separate questions. Your requirement was to use only the default model binder. The duplicate answers that question. – Patrick Hofman Nov 03 '17 at 09:41
  • @PatrickHofman I'll update question. Can you answer how to do this creating custom model binding + custom value provider? Thanks! – inser Nov 03 '17 at 09:49
  • No, I can't. But I will reopen your question so others can. – Patrick Hofman Nov 03 '17 at 09:50
  • @PatrickHofman thanks – inser Nov 03 '17 at 09:51

0 Answers0