ModelBinding on IOC resolved type
ModelBinding does not fully work on actions where we define a "base" type as parameter.
For instance, in a "framework library", I define this action
[HttpPost]
public IActionResult CreateClient([FromServices]ClientViewModelBase viewModel)
[...]
where ClientBase is define like this
public abstract class ClientViewModelBase
{
public string Name { get; set; }
}
In a specific application which uses my "framework library", I define a specific class which inherits from ClientBase
public class MyClientViewModel : ClientViewModelBase
{
public string AdditionalInfos { get; set; }
}
Of course in the startup, i add
services.AddScoped<ClientViewModelBase, MyClientViewModel>()
In my view, I have this
@model MyClientViewModel
<form asp-controller="MyBasicController" asp-action="CreateClient">
<input asp-for="Name" />
<input asp-for="AdditionalInfos" />
<input type="submit" value="Create client" />
</form>
When I post the data, I see on the browser developer tools that all data are correctly provided to the server But when I got the result of ModelBinding inside the action, there's only the "Name" property which is filled. The "AdditionalInfos" property is null.
The problem is that the ModelBinding uses the type provided in the signature of the action (my base type here) instead of the resolved/instantiated type. I think the ModelBinding must use the type of the instance (by reflection) to make all recursive stuffs instead of the ModelBindingContext.ModelType
I'd like to add the fact that there's a workaround to this issue by using the following method in the body of action
this.TryUpdateModelAsync(viewModel, viewModel.GetType(), "")
But this is just a workaround, not a long term solution
Model binding in general works with declared types and doesn't use DI to resolve model types.
You would have to write a custom model binder that has the appropriate logic to create instances of types other than the declared type.
cc @rynowak for FYI information.