Dynamic View Page, MVC without a View Model
Hello fellow techies on this roller coaster called life. It has been a while since my last post, I have been focusing on some other more important aspects of my life.
What I want to talk about in this post is the idea of a dynamic view page which removes the need for a View Model data transfer object. I have started to try this out on project that I am working on, for views that are essentially read only. All these views are concerned about is displaying data/information. I do not yet know how useful this is but I thought it was novel and will be exploring it’s usefulness. Plus, the lazy side of me likes the idea of not creating data transfer objects if possible.
Two side effects of this approach are the loss of the strongly typed Model on your view, which is a non-issue for a page without inputs. The second is the loss of intellisense (the very first time a member is used on a dynamic) when working with the Model in the view, which could be a minor loss in that you wont know something is wrong until you run it, but thats the way it goes.
To accomplish this you start off by creating a DynamicViewPage that inherits ViewPage. Have some overrides and new up some properties and you should be set.
public class DynamicViewPage : ViewPage { private ViewDataDictionary<dynamic> _viewData; public override void InitHelpers() { base.InitHelpers(); Ajax = new AjaxHelper<dynamic>(ViewContext, this); Html = new HtmlHelper<dynamic>(ViewContext, this); } protected override void SetViewData(ViewDataDictionary viewData) { _viewData = new ViewDataDictionary<dynamic>(viewData); base.SetViewData(_viewData); } public new AjaxHelper<dynamic> Ajax { get; set; } public new HtmlHelper<dynamic> Html { get; set; } public new dynamic Model { get { return ViewData.Model; } } public new ViewDataDictionary<dynamic> ViewData { get { if (_viewData == null) { SetViewData(new ViewDataDictionary<dynamic>()); } return _viewData; } set { SetViewData(value); } } }
Now your view needs to inherit from DynamicViewPage.
Inherits="Web.Views.DynamicViewPage"
In your controller you can ask your persistence abstraction of choice for some data and return it to the view.
public ActionResult Index() { IEnumerable<dynamic> foos = FooQueries.GetAll(); return View(foos); }
Where this can get interesting is when you have a linq provider that returns dynamic objects. Then essentially your domain model is king and you eliminate a lot of DTOs. That’s all I’ve got for now. I attached a sample application that demonstrates the dynamic view, enjoy!