Monday, December 29, 2008 12:18 PM
DmitryR
ASP.NET MVC View Engine using VB.NET XML Literals
[Update for ASP.NET MVC RC available]
The code in the attached ZIP file implements a custom View Engine for ASP.NET MVC Beta using VB.NET XML literals. Instead of traditional ASP.NET pages, the views are implemented as VB.NET classes.
The package contains a Visual Studio solution with two projects (the standard ASP.NET MVC starter template rewritten to use VB.NET XML views, and the library implementing the view engine), the license document, and README document.
Notes:
View engine registration is done in GLOBAL.ASAX in Application_Start method:
ViewEngines.Engines.Add(New VbViewEngine)
VbViewEngine, instead of searching directories for files, looks for a class derived from VbView named ActionName in namespace *.Views.ControllerName in the assembly of the controller.
ASPX, MASTER and ASCX files implementing MVC views are replaced with VB classes derived from VbView. Many ASP.NET concepts have direct analogs in VB.NET (or OO world in general). For example, a master page get replaced with a base class. Here is how Index view looks in VB.NET:
Namespace Views.Home
Public Class Index
Inherits SiteMaster
Public Overrides Function RenderContent() As XElement
Return <div>
<h2><%= Xhtml.Encode(ViewData("Message")) %></h2>
<p>To learn more about ASP.NET MVC ...</p>
</div>
End Function
End Class
End Namespace
The entire application is compiled into one assembly. There are no ASPX files that need to be deployed.
Unfortunately HTML helpers that come with ASP.NET MVC are not usable from VB.NET XML views because HTML helpers return strings. XHTML helper class has been added that has [some of] the methods found on HTML helper -- they return XElements instead of strings. Here is the implementation of validation summary helper using VB.NET XML literals:
Public Function ValidationSummary() As XElement
If _viewData.ModelState.IsValid Then
Return Nothing
End If
Return <ul class="validation-summary-errors">
<%= From e In _viewData.ModelState From m In e.Value.Errors Select _
<li><%= m.ErrorMessage %></li> _
%>
</ul>
End Function
The controller code in the starter template did not change at all, even though all the views have been replaced to use a different view engine. This is a good thing -- it validates the separation of concerns in MVC.
Your feedback and suggestions are most welcome!
Thanks,
Dmitry