Third Party View Engines
Everything in the MVC framework is pluggable. Any component you use can be replaced from custom value providers to custom model Meta data providers to custom controller factories. The same is true for the View Engines.
Microsoft provides two View Engines, the WebForm View Engine and Razor, and there are a couple of different third party options available as well. Much like we see with the programing languages, different View Engines may make it easier to transition to the MVC framework depending on your background.
If you are new to Web Programming all together, Razor may be your best bet.
If you transitioning to MVC from a classic ASP or even an ASP Web Form background, the WebForm View Engine may be your best bet.
Published in 2010. Jason Haley goes through an extensive review of the 2 most popular Third Party View Engines comparing them the Web Form and Razor.
He follows the same pattern for each View Engine so that you get a solid comparison comparing apples to apples to make it easier to evaluate the relevant strengths and weaknesses.
To facilitate his comparison, Jason converted the Nerd Dinner view’s to each View Engine.
Since NHaml and Spark are also used or ported from alternate web platforms, they may also provide a smoother transition into the MVC world.
The important thing to remember is that you have options.
Spark View Engine [Spark]
Published in 2012. This is the main product page for Spark if you want to download it and try it out for yourself.
The main goal with Spark is to “allow the html to dominate the flow and the code to fit seamlessly.”
The other main selling point for Spark is if you are already familiar with Castle Project MonoRail. This is the same View Engine.
Published in 2013. his is the main product page for NHaml if you want to download it and try it out for yourself.
NHaml is a DotNet port of the Rails Haml view engine. If you are already familiar with this, NHaml may be a natural transition for you.
Working with the Razor Engine
Published in 2010. Rachael Appel steps us through from start to finish creating a Razor View. She steps you through from creating the initial project to adding a model to creating a controller, and adding the View and showing not on the final look but also the resulting HTML.
At each step along the way, she includes nice screen shots that show what the project will look like, or the dialog box in Visual Studio or what IntelliSense may look like in the editor.
The Razor View Engine Basics [Blog]
Shay Friedman takes as on an often humorous tour through some of the ins and outs of the mechanics of code in a Razor view. He talks about the shock of not having to end a code segment, Code Blocks, adding a literal @ into your mark-up.
The venerable Phil Haack provides the magic decoder ring for translating between Razor syntax and Web Form syntax.
You should immediately see how much more succinct Razor is than Web Forms.
He covers all the basics and has kept it updated with MVC4 syntax.
This is a good page to keep book marked
Mike Pope explains one of the most frustrating aspects of converting from MVC2 to MVC3. Starting with MVC3 strings are automatically encoded to prevent RAW html from accidently being displayed.
This was done for security purposes but also frustrated many developers who had perfectly fine MVC2 applications break in MVC3.
Adding Dynamic Content to a Razor View
In this blog, Justin Schwartzenberger outlines a strategy for running stored text through the Razor View Engine and embedding this parsed text into a view. The idea here is that this would be separate content from the rest of the application and would constitute a content management system of sorts. The idea is intriguing and offers a great introduction to the RaorEngine project on nuGet.
The approach outlined could also be used to support user defined email templates. You could associate an interface with the template and as long as the Model implemented the interface, you could handle mapping it properly. Once you get comfortable with this approach, this opens up a lot of possibilities.
As we will see a little later on, this can be combined with custom view engines to create some exciting possibilities.
This github project exposes a library giving you the ability to programmatically invoke a Razor like compiler.
If you have any intention of allowing your users to specify formatted structured content on their own this is an invaluable library to have.
You may want to do this to allow:
- An admin to update a message of the day
- An admin to rework email templates
- A power user to author context aware help documentation
- Marketing to provide announcements or welcome text
Using Dynamically Typed Views
I wish there were more blogs like this. Rick Anderson takes a simple View and shows how this view could be implemented with a strongly typed model, a dynamic model, and the ViewBag.
Rick doesn’t go into why you would chose these other options, but he does a nice job of comparing the syntax among these three approaches. This makes a nice reference for reviewing this syntax.
In the blog, Greg Shackles answers one of the burning questions that I have long about dynamically typed views. Why bother?
It always seemed to me that the deck was stacked in favour of the strongly typed Views.
Greg argues for the use of dynamics with Partial Views. The partial view may be used with multiple views who may not all have the same model. As long as the individual models all expose the properties needed by the partial view, they can still be passed to the partial view as long as it is expecting dynamic.
Even this scenario is a bit of a stretch though. You can also solve this problem with interfaces and keep IntelliSense or use Child Actions which we will see shortly.
Using HTML Helpers
ASP.NET MVC 3 Razor View And HTML Helpers [C# Corner]
The Razor View Engine introduced a new syntax for defining HTML helpers. Previously the only option was to use extension methods against the HtmlHelper object. This required that the helper logic needed to be expressed in code and not markup.
Now we also have Inline helpers that can be expressed in markup.
These two options are analogous to Custom Controls vs. User Controls in ASP.NET.
In this article, Jadish Matthews steps through creating an HTML Helper using both syntaxes. From a usage perspective there is no difference, but from an ease of development / maintenance the difference is potentially substantial.
Here Scott Gu introduces us all to Layouts and Sections in the world of Razor. If you are transitioning from WebForms to Razor or from ASP.Net to Razor in MVC, Sections are asp:Content and Layouts are your mater pages only without the awkward naming conventions.
Scott steps us through modifying a simplistic _Layout, introducing the important @RenderSection syntax and the control that the layout can exert over required content. We then see how we can fill in the detail in individual views with the @Section syntax. Then he shows some of the possibilities that you can get by conditionally determining whether or not a section has been defined. Using this strategy, you could easily define a layout page that could support sidebar on the left or right or no side bar at all depending on which sections are defined in individual views.
David Ferguson starts with the question “"In web forms I used to do ‘x’ can that be done in MVC?”, in this blog he answers that question for Master Pages.
This creates an ideal quick reference for anyone already familiar with web forms looking to make the transition to Razor. Much of this information is covered in Scott’s blog as well, but this may be more accessible if you are making the transition from WebForms.
Once you start playing around with Layouts, you will quickly find that they can be nested. You may want to do this to have a standard look and feel for the site as a whole but have subtle differences between Areas or subtle differences between authenticated and not authenticated.
Whatever use you put it to, nested layouts is a tool at your disposal. In this blog, Marcin Doboz delves into some of the subtle nuances in dealing with nested layouts. Specifically he addresses the challenges dealing with passing sections from layouts to sublayouts down to the actual view.
Using Partial Views
Rachel Appel steps through and gently explains Partial Views. When you first get started, it is easy to dismiss partial views as nothing more than User Controls. While they do share many common features, there are differences as Rachel explains.
Partial Views are substantially lighter weight than user controls.
Using Child Actions
Shravan Jumar Kasagoni provides a gentle introduction to this attribute. He also provides a good explanation for why you might want to do this.
In essence this allows you to create an action that cannot be called client side. This allows you to reuse the action and associated View from multiple locations without being exposed to unknown callers.
The alternative to child actions would be partial views, but this would require that the model for the partial view be embedded in the model for each view using the partial view. If this is the only use for the partial view’s model, this may be excessive.
Child actions allow us to reuse the functionality of the partial view without having to add unneeded data to multiple Models.
Tugberk Ugurlu outlines the basic strategy for combining the ChildAction attribute with the OutputCache attribute to allow you to cache part of a page. Caching can be a great way to make a website more responsive. This strategy provides guidance on how to get very granular on what is cached.
Bipin Joshi shows how to use Child Actions to essentially push to a Controller the logic of which partial view to render. This allows you to keep the conditional logic out of your View and improve the usability of the individual components.
This blog doesn’t deal discuss the ChildAction attribute, but it builds on a similar theme. Here Radu Enucă builds an ActionInitializationRequired Filter that allows him to specify an action that must be called before a given action is called.
In essence this creates something very similar to the ChildAction except it can be called client side. You have the flexibility of calling the action from the client side while still being able to verify that the context for calling the action is maintained. Calling such actions client side opens up some exciting opportunities that we will explore shortly.
Creating a custom view engine
Everything in the MVC framework is designed to extended, or replaced with your own implementation. This includes the View Engines used to interpret the mark up in your views. Swapping out the View Engine sounds like a daunting task, and your first reaction may be “why would I want to do that? Turns out aside from being an interesting exercise in extensibility, there are some compelling reason to roll your own View Engine.
Nick Beradi takes us through the steps to create your own View Engine with the goal of changing where the framework looks for the view and their components. He does this by defining his own ViewEngine overriding the values for key properties telling the framework where to look for Master Pages, Views, and Partial Views. In the CreateView and CreatePartialView methods, he keeps his job simply by creating a new WebFormView. He could just as easily have created a new RazorView.
If you are trying to incorporate MVC into a legacy ASP.Net application, you may need to do something similar to have more control over where files are expected to be.
One word of caution, this technique can be used to steam line and simplify your project structure or it could be used to complicate matters making it harder to maintain your project. Make sure you have a compelling reason to take this step beyond simply being able to.
Creating a Custom View Engine in ASP.NET MVC [Singing Eels]
Timothy Khouri takes this customization to the next level. Not only does he
define a new ViewEngine, he also defines a new View along with a new language
to be used in the view. His HoTMeaT language isn’t really explored in
the article, but he does make it available as a project download. This is some
You may want to do something along these lines, if you wanted to provide a simplified language for allowing non-programmers to maintain the Views. Perhaps you have someone in marketing who could handle straight HTML but does not need everything that Razor brings to the table. You could provide a simplified language supporting a subset of traditional databinding.
Phil Haack presents an interesting concept for extending the Razor View Engine. As you probably already know, the mark up in you View gets compiled into a class derived from WebViewPage. Phil’s trick is to add your own class in this hierarchy. Instead of deriving from WebViewPage, the class generated by your mark-up derives from CustomWebViewPage which in turn derives from WebViewPage.
This allows us another configuration point. Phil exploits this strategy to provide a new Html5Helper object modelled after the Html helper but addressing Html5 specifically. You could do something similar to add your own project specific properties or logic. Just remember that the goal is to keep view logic as simple as possible. Anything not directly related to displaying the contents of the view should generally do somewhere else.
Creating a custom View Engine for ASP.NET MVC leveraging Text Template (T4) engine for rendering the view [Blog]
Anoop Madhusudanan investigates creating a new View and ViewEngine with a twist. He incorporates the power or T4 into the mix. If you are not familiar with T4, you should make it a goal to get familiar with it. Anoop does a good job showing how all of the pieces fit together to create the View and ViewEngine and the idea of using T4 opens up some interesting possibilities.
This may not be too useful in itself beyond being a great exercise of what is possible, but it does have some serious wow factor.
Nick Harrison pulls the pieces together to build a new ViewEngine and accompanied View this time with the goal of creating an Excel files. Nearly every example you will find on the Internet, the goal of the View is to output HTML, but that is not the only possibility.
Following Nick’s example, you can separate the content and format of the resulting spread sheet just as you wold with HTML with traditional views.
For this example to be truly useful, you will need to flush out a more complete grammar for describing the spread sheet in the “view”, but those details really are dependent on your specific needs.
Another interesting point with this implementation showcases creating a strongly typed View and sharing this type information between the Controller, ViewEngine, and View.
This same pattern could be followed to create View Engines for Word Documents, PDFs or other file formats that your client periodically requests.
Client-Side View Considations
The View is the area that spans between the server and client. The implementation is not limited to what can be done on the server. Some of this functionality can be pushed off to the client side. Generally this may be done to create a richer user experience and make the application more responsive.
Whenever you do push functionality to the client side/ pay extra attention to security. Defence in Depth tells us to repeat validation on the server side. Even when you move business logic to the client side, it is still not to be trusted without first being validated and sanitized.
Moving logic closer to the client is for the benefit of users using your application as designed. All of the logic needs to be repeated and validated server side.
Client-Side Markup with JQuery Cloning and Templates [Simple-Talk]
Cloning allows you to take an existing DOM element and duplicate it and all of its descendants. You then manipulate key properties as needed and then add it back as needed. Depending on the number of updates needed, this can be a trivial task or rather complex.
MVC Techniques with jQuery, JSON, Knockout, and C# [The Code Project]
Mark Caplin provides a tour de force overview of using jQuery and Knockout on the client side and communicating with MVC on the server side through JSON. He covers a substantial amount of material. This is worth several careful, detailed reads.
The author skims over the details for data binding with Knockout.js. Fortunately, Syncfusion has a great resource with their Knockout.js Succinctly eBook. This is a free eBook and a great reference even if you are already familiar with Knockout.js.
Proper use of jQuery to communicate back to the controller means that you can often avoid a full round trip back to the server. You can instead send minimal parameters back and get minimal data back as JSON easily interpreted on the client side. This article uses jQuery’s post method to communicate with the controller. I recommend using the Ajax method and explicating telling jQuery that we are expecting JSON back. jQuery will automatically parse the response for you.
The main point to take away here is that these various components do play well together. They can easily be combined to create some dynamic rich interactive solutions. You have to decide for your own application and users what makes sense to push down to client side processing.