Well, I’ve tried several different implementations for sending data to master views. One of the problems was in basing the ViewModels off of a common MasterViewModel. This made sense for some view models, but not others. Let me explain…
Using AutoMapper, a db query could be mapped to a type, and returned as an ienumerable of a given view model type. If that view model was based off the master view model then certain data elements would be repeated. I wanted a way to avoid that.
My solution was NOT to use an abstract MasterViewModel class. Instead, I created the following wrappers:
Presentation - provides all common properties and some SelectList manipulating methods.
ItemPresentation<T> : Presentation - adds an Item property of type T.
ListPresentation<T> : Presentation - adds an Items property of type IEnumerable<T>.
To get these working, I needed to add a few methods to my BaseController class…
[NonAction]
private ActionResult Presentation(Presentation presentation)
{
// begin common property setting
// end common property setting
return View(presentation);
}
[NonAction]
protected ActionResult ItemPresentation<T>(T item)
{
ItemPresentation<T> presentation = new ItemPresentation<T>();
presentation.Item = item;
return Presentation(presentation);
}
[NonAction]
protected ActionResult ListPresentation<T>(IEnumerable<T> items)
{
ListPresentation<T> presentation = new ListPresentation<T>();
presentation.Items = items;
return Presentation(presentation);
}
Then in the derived classes, I’d return something like the following, instead of a call to View():
return ListPresentation<CodeManagerModel>(codeService.GetCodeManagerModels());
return ItemPresentation<CodeEditModel>(codeService.GetCodeEditModel(id));
The site.master would be based off of ViewPage<Presentation> so it could read all of the data it needs. The actual view pages would be based on something like ViewPage<ItemPresentation<CodeEditModel>> and this works.
I know it’s backwards from what most people do, but I like it. Is there any inherent reason I shouldn’t do it like this?