Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC model binding to interfaces

I have created an OrderFormViewModel which looks something like

public class OrderFormViewModel 
{
    public IOrderDetails { get; set; }
    public IDeliveryDetails { get; set; }
    public IPaymentDetails { get; set; }
    // ... etc

    public SelectList DropDownOptions { get; set; }
    // ... etc

}

This goes to my Create view, where each section (i.e. delivery details, payment details... etc) is then passed to a partial view which captures the necessary fields.

I thought this was all quite neat until I ran it and realized of course that the MVC model binder doesn't know how to instantiate any of the interfaces.

Is there a way to resolve this somehow?

I'm also trying to learn DI using the Unity container, so I'm trying to avoid having references to any concrete classes in my UI project (model is in a separate project).

like image 564
fearofawhackplanet Avatar asked Jun 11 '10 14:06

fearofawhackplanet


2 Answers

One solution is to make a custom model binder, but this path means you will need to go through the effort of translating form elements to properties on your object. However, you have complete control over which implementation of IOrderDetails gets used, for example, or you can have your DI give you the right concrete type using it's configuration.

like image 123
Tejs Avatar answered Oct 02 '22 00:10

Tejs


A possible solution might be here (under Interface Binding Filter vs View Model Binding): http://codetunnel.com/aspnet-mvc-model-binding-security/

like image 23
HonourCode Avatar answered Oct 02 '22 01:10

HonourCode