Stefan Rusek | ASP.NET MVC Views in Xronos

ASP.NET MVC Views in Xronos

Tuesday, December 09, 2008

With the release of Xronos v0.1 comes an overhaul of how it works with ASP.NET MVC. First I removed the ASP-like syntax. The syntax was familiar, but it turns out that the syntax did not actually do anything helpful, because (pr) ends up making cleaner code. If that was the only change, then writing views in Xronos would be pretty lame. The new system is modeled after ASP.NET MasterPage system.

Enabling the ViewEngine is the first step toward using Xronos with ASP.NET MVC. Add a line to the Application_Start event in your Global.asax.cs file, before the call to RegisterRoutes(). The ViewEngine constructor takes any number of path names to files to compile immediately.

    new System.Xronos.Web.Mvc.ViewEngine("~/Views/Shared/Library.x");

Normal pages are simple to create, just write a (render) function that prints out your HTML:

(defn render [] (pr 
    "<html><head><title>" (get viewdata "Title")  "</title></head>" 
    "<body>Yay! it works</body></html>" 

This is fine and all, but most of the time you want a bunch of views that share a common layout. If you are familiar with how master pages work in ASP.NET, then Xronos master pages will be very familiar to you. In the master page file you need to have a (render) function and a params variable defined.

; ~/Views/Shared/Site.Master.x 
(def params) 

(defn header [] ... ) 
(defn footer [] ... ) 

(defn render [] 
    ((:body params)) 

Then in your page you simply specify that you are using a master page and the content of the params.

; ~/Views/Home/Index.x 
(def master "~/Views/Shared/Site.Master.x") 
(xronos/refer 'mvc) 

(defn renderItems [] 
    (dorun (map blog/renderItem (get viewdata "Items"))) 

(def content {:body renderItems})

Since Xronos compiles each file in its own namespace, each page is isolated from each other and cannot access any other functions unless your library puts them in an accessible namespace

; ~/Views/Shared/Library.x 
(in-ns 'blog) 
(xronos/refer 'mvc) 

(defn renderItem [item] ... )

At the moment Xronos only supports writing views. Sometime soon-ish, I hope to make it easy to write entire MVC apps in xronos. In the meantime, it is still an awesome language to write MVC views.

Please log in or register to comment.