ASP.Net MVC 3 introduces Razor a new view engine

Posted: December 22, 2010 in ASP.Net, Asp.Net MVC
Tags: , , ,
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.

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


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

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

<div class="ui-body">

@RenderBody()

<div class="ui-footer">

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

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


@{

LayutPage = "base.cshtml";

}

@section menu {

<ul>

<li>Home</li>

<li>Login</li>

</ul>

}

@section footer {

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

}

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.

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.


@helper MethodName(arguments) {

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

}

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.


@helper ShowAlert(var msg, var status) {

@if(status == "error") {

@msg

} else {

@msg

}

}

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


<html>

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

<body>

<p>Below Error Found </p>

<div>

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

</div>

</body>

</html>

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s