X

New @model Keyword in Razor – ASP.NET MVC3

ASP.NET MVC 3 supports a new view engine called Razor. As we know ASP.NET MVC 3 has cool improvements using razor, which makes code clean & concise. One of the simple & cool improvement is @model keyword. Scenario is i want to create strongly typed view to display the list of person details. In .aspx…

ASP.NET MVC 3 supports a new view engine called Razor. As we know ASP.NET MVC 3 has cool improvements using razor, which makes code clean & concise. One of the simple & cool improvement is @model keyword.

Scenario is i want to create strongly typed view to display the list of person details. In .aspx view engine on top view in <%@ Page %> we use Inherits attribute to specify the model for a particular view.

Inherits="System.Web.Mvc.ViewPage<TModel>"

Inherits attribute at the top of the file that indicated that we wanted to derive the view from the “System.Web.Mvc.ViewPage<TModel>”. If you have used initial versions ASP.NET MVC 3(Previews) they also use same kind of syntax.

@inherits System.Web.Mvc.WebViewPage<TModel>

The Index.cshtml view look like this:

@inherits System.Web.Mvc.WebViewPage<IEnumerable<LayoutSample.Models.Person>>

@{
    ViewBag.Title = "Persons Details";
 }

If we observe @inherits syntax View is inherited from System.Web.Mvc.WebViewPage which is base class for the razor views, the same code we need to replicate in all the views in the application , which not necessary, this involves in duplicating the same line code in all the views in the application breaks DRY principle. But the goal of the razor is to make the code more clean & concise , so from ASP.NET MVC 3 beta edition onwards we have more cleaner syntax to specify the model in strongly typed views, i.e.: using @model keyword, so the syntax look like this, on top of view.

@model TModel

using @model keyword we need not to specify the base class in the razor views, until & unless, we want to inherit our views from custom base class.

The Index.cshtml view look like this from asp.net mvc 3 beta onwards:

@model IEnumerable<LayoutSample.Models.Person>

@{
    ViewBag.Title = "Persons Details";
 }

@model keyword is may be simple enhancement, but which save lot keystrokes & makes the look more clean & concise.

Categories: ASP.NET MVC
Shravan Kumar Kasagoni: