ASP.Net MVC 3 introduces Razor a new view engine
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.
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 )
<div class="ui-body">
@RenderBody()
<div class="ui-footer">
@RenderSection("footer", optional:true )
[/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>
[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>