开发者

MVC model binding to interfaces

开发者 https://www.devze.com 2023-01-02 23:18 出处:网络
I have created an OrderFormViewModel which looks something like public class OrderFormViewModel { public IOrderDetails { get; set; }

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 reso开发者_Python百科lve 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).


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消