Using Brail View Engine with ASP.NET MVC
Join the DZone community and get the full member experience.
Join For Freeafter one week of staying away from this blog and resting for a short while, now it’s time to get back to regular blogging with a new post! hopefully i’m going to publish more posts about new topics in the near future and one of these topics is asp.net mvc which is also the topic of the current post.
as you may know, asp.net mvc (like other implementations of the mvc pattern) applies view engine mechanism as a way to replace the rendering methods of the applications, and while the built-in view engine would be the most commonly used engine with the asp.net mvc, community members have started creating alternative engines to use in their mvc applications. at the moment, there are a few implementations all as a part of mvccontrib open source project that are ported from other technologies like java and monorail.
i’m not very positive about the usage of ported material from other technologies, but it’s the only option at the moment, so we have to choose one engine from this finite list of ported engines. recently i’ve been evaluating all these engines and tried to use them in simple applications. while doing this, i believed that some community members have written good guides about using nhaml or nvelocity in good details but there wasn’t something analogous for brail (except its online documentation ), so this post is being written as such a guide.
overview
brail is a view engine designed for monorail and is a part of castle project in which you are able to build text-based views for your applications to replace the default view engine with something more relevant for some tasks. brail is also ported to the asp.net mvc and is a part of mvccontrib project available on codeplex that is regularly updated with the latest asp.net mvc previews with a rich set of additional features that are very helpful.
brail works as an alternative for the built-in asp.net view engine that uses .aspx and .master file extensions to store page and master files. brail uses .brail extension names, and like its original version, it may use .brailjs extension as well but i haven’t tested it yet.
in brail files you define your master layout or page interface with html/xhtml/css code and use its syntax to render dynamic data (as i’ll introduce in a moment).
there are some certain steps to get started with brail for asp.net mvc that are listed here:
- add required references to your project.
- configure your project.
- add brail view engine to the asp.net mvc view engines collection.
- create your layout and page brail files with your desire user interface and regarding the syntax of brail files.
as you see, these steps are pretty simple and easy to follow, and more interestingly, like any other view engine, you can replace the engine without touching anything in your logic (controller) or model because it’s mvc and that is what it’s supposed to be!!
like asp.net mvc default engine you need to care about naming convention and store your view files in folders with the same name as your controller class within views folder but for brail you must store your master files in layouts sub-folder in views folder.
having this background, let me show you how to get started with brail quickly and easily, but before stepping into the main discussion, let me point that you must have the most recent build of mvccontrib project by grabbing your copy at its codeplex workspace . binary release package is sufficient for using the features but you can also take a look at the source code for further learning and inspirations.
references
the first and obvious step is adding some references to your asp.net mvc project in order to be able to apply mvccontrib features such as brail view engine, and this step consists of a general step for all features included in this project as well as one extra step for each specific feature: in general you need to add a reference to mvccontrib assembly in your project, but you may also need to include extra references for the specific feature that you’re going to use. for brail view engine case, you need to add references to boo language and mvccontrib.brailviewengine assemblies, so all in all you must have these references in your projects:
- mvccontrib
- mvccontrib.brailviewengine
- boo.lang
- boo.lang.compiler
- boo.lang.extensions
- boo.lang.parser
you can find boo language assemblies in many sites but the easiest one is in the bin folder available in the root of samples folder in mvccontrib binary download package.
configuration
the second step is, configuring your asp.net mvc application to use brail, and this is possible by some modifications in web.config file which would be familiar to any .net developer. you add a new section definition and the specific section for <brail /> element.
the following piece of code shows how you can configure your application to use brail view engine.
<configsections>
<section
name="brail"
type="mvccontrib.brailviewengine.brailconfigurationsection, mvccontrib.brailviewengine"/>
</configsections>
<brail
debug="true"
savetodisk="false"
batch="false"
commonscriptsdirectory="commonscripts"
savedirectory="compiledviews" />
it’s obvious that you can configure brail in a few ways such as enabling debuggable code and generating/storing compiled scripts on the disk.
setup
the third step is, adding your brail view engine to asp.net mvc view engines list, and it’s a kind of familiar pattern for asp.net net mvc developers to do this in global.asax file in one line of code.
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;
using system.web.routing;
using mvccontrib.viewfactories;
namespace brailsample
{
public class mvcapplication : system.web.httpapplication
{
public static void registerroutes(routecollection routes)
{
routes.ignoreroute("{resource}.axd/{*pathinfo}");
routes.maproute(
"default",
"",
new { controller = "home", action = "index" }
);
routes.maproute(
"about",
"about/",
new { controller = "home", action = "about" }
);
// add the view engine
viewengines.engines.add(new brailviewfactory());
}
protected void application_start()
{
registerroutes(routetable.routes);
}
}
}
brailviewfactory is the view factory that you should add to the list of asp.net mvc view engines and that’s it!
besides, it’s worth mentioning that for my sample i have to build views for the homepage and about page that will be handled by a single homecontroller in which i have two action methods that act like any other action method.
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;
using system.web.mvc.ajax;
using brailsample.models;
namespace brailsample.controllers
{
[handleerror]
public class homecontroller : controller
{
public actionresult index()
{
viewdata["title"] = "home page";
viewdata["message"] = "welcome to asp.net mvc!";
viewdata["time"] = datetime.now;
return view("index", "master");
}
public actionresult about()
{
viewdata["title"] = string.format("about");
var keyvan = new person();
keyvan.name = "keyvan nayyeri";
keyvan.birthday = datetime.parse("10/11/1984");
keyvan.hometown = "kermanshah, kurdistan";
keyvan.degree = "bachelor of science";
return view("about", "master", keyvan);
}
}
}
if you’re curious about person class, its code is as simple as what you see below.
using system;
using system.collections.generic;
using system.linq;
using system.web;
namespace brailsample.models
{
public class person
{
public string name { get; set; }
public datetime birthday { get; set; }
public string hometown { get; set; }
public string degree { get; set; }
}
}
layouts
in brail engine layouts have the same responsibility as masters in the built-in asp.net mvc view engine, and they follow the same syntax as other brail files. note that you must add your layouts under layouts folder with .brail extension, and you logically would build your general site layout in these files.
for my sample i have created a basic layout with this code:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en"
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>${title}</title>
<link href="${siteroot}content/site.css" rel="stylesheet" type="text/css" />
</head>
<body>
${html.actionlink('home','index')}
${html.actionlink('about me','about')}
<div>
${childoutput}
</div>
</body>
</html>
i’d point that you can refer to view data parameters with ${parametername} syntax as i used for ${title} and brail has some preserved parameters like siteroot and childoutput (and some other parameters) that can be used as placeholders for site root url and the content of child pages respectively.
usage
the final step, as i had stated, is, building your page files with .brail extension. for my sample, i require two files: one for the index page and another for the about page.
the code for the index file is simpler because it just extracts two parameters from the view data parameters list and displays them.
<h1>${message}</h1>
current time is <strong>${time}</strong/>
but about file does something more and retrieves its data from model object directly.
<h1>about ${viewdata.model.name}</h1>
birthday: ${viewdata.model.birthday.tostring("mmmm dd, yyyy")}<br />
hometown: ${viewdata.model.hometown}<br />
degree: ${viewdata.model.degree}<br />
test
running my sample application, i see the expected output.
you can download the sample code package for this post from here .
Published at DZone with permission of Keyvan Nayyeri. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
What I Learned From Crawling 100+ Websites
-
How To Scan and Validate Image Uploads in Java
-
Which Is Better for IoT: Azure RTOS or FreeRTOS?
-
Building a Java Payment App With Marqeta
Comments