1

I have a Ad Model like below:

public class AdModel
{
    public int Id { get; set; }

    public string Title { get; set; }
}

And I have lots of derived classes as well like.

public class CarAdModel : AdModel
{
    public int? Kilometer { get; set; }
}

My Web Api Controller is like:

public class AdController : ApiController
{
     [HttpPost]
     public async Task<IHttpActionResult> Post([FromBody] AdModel adModel)
     {
         //db insert
         return Ok();
     }
}

If I post a derived object like CarAdModel from my AngularJs app, I only get those properties which belong to AdModel, can I get derived object on Post action?

Usman Khalid
  • 3,032
  • 9
  • 41
  • 66

1 Answers1

1

you need create custom binder for AddModel or common binder like this and some field for restore target class:

public class TypeModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ModelType");
            var type = Type.GetType((string)typeValue.ConvertTo(typeof(string)), true);
            var model = Activator.CreateInstance(type);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
            return model;
        }
    } 

In my example model, the field "ModelType" contais full typename of the class

Aage
  • 5,932
  • 2
  • 32
  • 57
vhostt
  • 66
  • 5