Mvc icon indicating copy to clipboard operation
Mvc copied to clipboard

ModelBinding on IOC resolved type

Open marcusien opened this issue 9 years ago • 2 comments

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

marcusien avatar Oct 16 '17 09:10 marcusien

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

marcusien avatar Oct 16 '17 09:10 marcusien

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.

Eilon avatar Oct 19 '17 19:10 Eilon