Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 ViewModel With Child Interface

Is there a way to handle this without custom Model Binding?

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 issue I'm having is I get an error in the default model binder because it doesn't understand which implementation of IJob to instantiate. When I created the MyViewModel, I set an instance of FullTimeJob into its Job property. I guess ASP.NET can't retain the implementation type?

What's the best practice solution for this?

like image 878
Adam Levitt Avatar asked Dec 22 '12 13:12

Adam Levitt


1 Answers

Views are just data carriers between UI and controller. So you can simply add Id and CompanyName properties to your view. Because all you want to do is getting Id and the company values from UI. It might not be important whether or not it is a internship or fulltime job while getting data from UI. It may be important when you are processing the data you got from UI but it is not View's responsibility.

like image 152
Mehmet Ataş Avatar answered Nov 12 '22 17:11

Mehmet Ataş