开发者

ASP.NET MVC 2 Using an interface to strongly type a partial

I'm experimenting with ASP.NET MVC2, in particular viewmodels and partials. My question is: Is it ‘valid’ or ‘right’ to have your partials strongly typed against an interface and the have your viewmodels implement that interface if the view uses the partial?

To illustrate, say I have a Product form partial (strongly typed against IProductFormViewModel) which is used in both the Edit and Create views. These views are strongly typed against ProductEditViewModel and ProductCreateViewModel which implement the IProductFormViewModel.

The be开发者_开发百科nefit being that the corresponding POST actions for Create and Edit take ProductCreateViewModel & ProductEditViewModel objects respectively.


Edit: If the partial has its own dedicated viewmodel (ProductFormViewModel) and each of the ProductEditViewModel & ProductCreateViewModel expose a property of type ProductFormViewModel which is passed to the partial, then when the form is submitted the model binding of ProductEditViewModel & ProductCreateViewModel doesn't work as the Edit and Create actions expect their respective object types...thats the reason for the approach.


You may have problems when your interfaces for your different partials expose the same property name e.g. name. You would then have to explicity implement the interface which would then cause problems with your model binding.

Otherwise it should work.


Yes, this seems a valid approach.


Interfaces are essentially contracts that need to be fulfilled by implementing classes. but in case of view engines i don't see any specific benefit of having you viewmodels implement an interface because at the end you have to instantiate the viewmodel in controller and pass it to the view and suppose you change implementation of ProductFormViewModel or EditProductViewModel, u still have to instantiate (populate) the object in controller and pass it to the view. so it does not achieve the same purpose as we do in repository pattern in conjunction with dependency injection. if you can tell what exactly u are trying to achieve by this approach, we might help.


Your approach is fine.

Or you could have a model specific to your partial and use composition instead, e.g.:

public class AddressModel
{
    public string Address { get; set; }
    public string Code { get; set; }
}

public class PersonModel
{
    public string Name { get; set; }
    public AddressModel Address { get; set; }
}

Then when redering your partial you pass it the correct model.

HTH

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜