If you ever get into a MVC ViewModel Error - No parameterless constructor defined for this object, then you got into a situation where you have a viewmodel that needs parameters. Example:
namespace Application.Web.Models { public class GameweekViewModel { public virtual IEnumerable<Book> BookList { get; set; } public BookSheelViewModel(IStoreDataSource db) { this.BookList = db.Books.ToList(); } } }
Once you post this model back to the controller, MVC will need to create a new instance and will not know how to. The easiest solution is to add a parameterless constructor to the Viewmodel:
namespace Application.Web.Models { public class GameweekViewModel { public virtual IEnumerable<Book> BookList { get; set; } public BookSheelViewModel() { } public BookSheelViewModel(IStoreDataSource db) { this.BookList = db.Books.ToList(); } } }
Another Solution is to use an IoC (Inversion of control) framework that handles the dependency injection for you.
Comments
Post a Comment