The question is not about MVC but more about code architecture.
I have a partial view that takes a CompanyModel
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CompanyModel>" %>
<%: Html.TextAreaFor(m => m.Name) %>
<%: Html.TextAreaFor(m => m.Location) %>
CompanyModel
public class CompanyModel
{
[LocalizedDisplayName("Name", NameResourceType = typeof(Resources.Views.CompanyBackground))]
public string Name{get;set;}
[LocalizedDisplayName("Location", NameResourceType = typeof(Resources.Views.CompanyBackground))]
public string Location{get;set;}
public CompanyModel()
{
var info = Project.GetCompanyInfo();
}
}
Project.GetCompanyInfo() is the DAL layer and gets data from the DB using Entity Framework
My question: what is the “nice” and correct way to fill CompanyModel?:
Solution 1
Create CompanyBag
public class CompanyBag
{
public string Name{get;set;}
public string Location{get;set;}
}
and Project.GetCompanyInfo() will return the CompanyBag and in the .ctor of CompanyModel I’ll fill the Model.
Solution 2
Project.GetCompanyInfo() will return CompanyModel (and thus no helper class is needed) and I’ll fill the Model in the .ctor of CompanyModel
Solution 3
maybe your solution?
UPDATE:
I have LoadController with Load action and this action is kind of a Factory. It will take list of views and will create them by reflection and then load to the page by Html.RenderPartial(viewName, viewModel). So, CompanyModel is just one example of the views and therefore I need each view to be independent.
So my question is: should GetCompanyInfo return a CompanyBag or a CompanyModel and I’ll fill the Model in the .ctor?
Thank you
Ok, following the question update, here’s my updated answer 🙂
I’m assuming the different Views
LoadControllerpopulates take different types ofViewModel, and eachViewModelis populated from a different part of the domain model. Here’s how I’d tackle that:Firstly, create each partial View as a strongly-typed subclass of
ViewUserControl<TViewModel>, soLoadControllercan figure out whichViewModeltype it needs for each of the Views it is told to create.Secondly, define an
IViewModelFactory<TViewModel>interface, and create one implementation for eachViewModeltype you require; each implementation will know how to create and populate itsViewModeltype from your domain model.Finally,
LoadControllerwould figure out the type ofViewModelit needs for each view it’s been asked to create, and use the appropriateIViewModelFactoryto create it.To avoid unnecessary overhead,
LoadControllercould find all the availableIViewModelFactoryimplementations at runtime, and keep a static store of them against the type ofViewModelthey create.So to sum up: I would populate
CompanyViewModelfrom aCompanyusing aCompanyViewModelFactory, I would populate aUserViewModelfrom aUserusing aUserViewModelFactory, etc. 🙂