ASP.NET MVC 4 ViewModel with a child interface

Is there any way to handle this without a special binding to the model?

public class MyViewModel { public string UserId { get; set; } public IJob Job { get; set; } } public interface IJob { public long Id { get; set; } public string CompanyName { get; set; } } public class FullTimeJob : IJob { // omitted for brevity } public class Internship : IJob { // omitted for brevity } 

The problem I am facing is a bug in the default binder, because it does not understand which IJob implementation should be created. When I created MyViewModel, I set the FullTimeJob instance to its Job property. I think ASP.NET cannot save the implementation type?

What is the best solution for this?

+7
source share
2 answers

Views are only storage media between the user interface and the controller. That way, you can simply add the Id and CompanyName properties to your view. Because all you want to do is get the company identifier and values โ€‹โ€‹from the user interface. Perhaps it doesnโ€™t matter if this is an internship or a full time job when getting data from the user interface. This can be important when you process data received from the user interface, but is not responsible.

+1
source

One option, although not particularly elegant, may be as follows:

 public class MyViewModel { public string UserId { get; set; } public FulltimeJob FulltimeJob { get; set; } public InternJob InternJob { get; set; } public IJob Job { get { return FulltimeJob ?? InternJob; } } } 

This gives you easy access to common properties through the Job property, while maintaining access to any class properties.

You can then check which property is populated in your POST controller methods and act accordingly.

0
source

All Articles