Thursday, January 10, 2013

Introduction to Razor in MVC

Razor is a view engine that is used in MVC 3 and later. Files use the file extension .cshtml.

One of the nice things is that it is unit testable with standard Visual Studio unit tests.

A cleaner and more elegant view engine than the default view engine.

You can use multiple view engines in the same project, including ones that third-parties have created.

Syntax

It is simpler to use than the Web forms engine syntax used by the default MVC view engine.

Default way: <%: Html.ActionLink(“Register”, “Register”) %>

Razor way: @Html.ActionLink(“Register”, “Register”)

You’ll notice there is no closing code block needed and the opening code block is just the @ sign which is easier to type. It will still automatically encode the string as well.

Code Block

if you are using Html.BeginForm or other blocks of code you can do something like this. No need for the old <% %> tags

@Html.BeginForm() {
… <some html here>…
}

Comments

You can do a server side comment with

@”
Comment here
”@

Layouts

Razor uses Layouts instead of Master Pages. They are just like other Razor files except it uses @RenderBody() to designate where content should be. Each view has a Layout property that you can set to the layout file. Alternatively, you can define the default by creating a file that is has a special name_ViewStart.cshtml. That way you don’t need to specify the layout property on each view. You can also put the file in subfolders in the View folder to have only the views in that subfolder be affected.

No comments: