ASP.Net MVC 3 introduces Razor a new view engine

1 minute read

I just read the great article Introducing "Razor" – a new view engine for ASP.NET by Scottgu. I found Razor more comfortable than the other view engines.
It's very easy to write code with Razor View Engine, it substantiates the write less and do more concept. There are lots of good stuffs in Razor.  However, I liked below things in Razor.
1) Instead of writing <% = %> for code block, we can just write @ and start our coding. Razor does not require you to explicitly close the code-block.
2) RenderBody and RenderSection are much powerful, they enables the layout re-useablity.</p>

The sections can be made optional so that any page can have the layout without having those sections defined.

Say we have one Base.cshtml page that has certain basic static html which can be used in multiple pages just like master page.

Base.cshtml

[sourcecode language="HTML"]

<div class="ui-left-menu">

@RenderSection("menu", optional:true&nbsp;)

<div class="ui-body">

@RenderBody()

<div class="ui-footer">

@RenderSection("footer", optional:true&nbsp;)

[/sourcecode]

Now, say there is one page which wants to inherit from the base.cshtml page and then we can write bellow code for child.cshtml.

child.cshtml

[sourcecode language="HTML"]

@{

LayutPage = "base.cshtml";

}

@section menu {

<ul>

<li>Home</li>

<li>Login</li>

</ul>

}

@section footer {

<p> Hey I am in footer now... :)</p>

}

[/sourcecode]

When we render child.cshtml as a view-template again, it will now combine the content from the base.cshtml and child.cshtml page, integrating the two new custom section overrides in it.

</span></div>

3) Last but not lease powerful thing is Declarative HTML Helpers . However, in ASP.Net MVC 3 (preview 1) this feature is not yet included. HTML helpers are just like C# methods which we create once and call it from various places from our project. We can define reusable helpers using a @helper { } declarative syntax like below.</p>

[sourcecode language="html"]

@helper MethodName(arguments) {

.....markup goes here....

}

[/sourcecode]

You can create one Helpers directory inside the View Folder and can put one helper.cshtml file inside that you can create one helper function let’s say ShowAlert method like below.

[sourcecode language="html"]

@helper ShowAlert(var msg, var status) {

@if(status == "error") {

@msg

} else {

@msg

}

}

[/sourcecode]

After creating above helper method, you can call ShowAlert method from any page.

[sourcecode language="html"]

<html>

<span style="font-size: small;"><head></head></span>

<body>

<p>Below Error Found </p>

<div>

@ShowAlert(Model.User.Message,"error")

</div>

</body>

</html>

[/sourcecode]

 

</span></div>