ASP.NET MVC 3 Beta: Strongly-typed views in Razor

One of the new features of Razor view engine is support for strongly-typed models. In this posting I will show you how to use strongly-typed model with Razor using simple view page.

Model

To illustrate strongly-typed view we need some object that we can use as model. I have ContentPage and ContentPagesModel classes. First of them represents primitive content page and the other the model that handles content operation. Okay, there is one method available right now in our model.


public class ContentPage
{
   
public string Title { get; set
; }
   
public string Description { get; set
; }
}

public class ContentPagesModel
{
   
public ContentPage
GetAboutPage()
    {
       
var page = new ContentPage
();
        page.Title =
"About us"
;
        page.Description =
"This page introduces us"
;

       
return page;
    }
}

Controller action

Next let’s take Home controller and and modify action method called About(). This action method displays our About view. In this method we will instantiate model and ask about page from it. The instance of page is used as a model for About view.


public ActionResult About()
{
   
var model = new ContentPagesModel
();
   
var
page = model.GetAboutPage();

   
return View(page);
}

Strongly-typed model in Razor

Now let’s open About view that we got out-of-the-box when we created new project. After some little modifications this view likes this.


@model Experiments.AspNetMvc3NewFeatures.Razor.Models.ContentPage
@{
    View.Title = Model.Title;
} 
 

<h2>About</h2
>
<
p>
     @Model.Description
</p
>

First line of the view sets type of model. And in the browser our view looks like this.

Razor strongly-typed view

Conclusion

Razor supports now strongly typed views and this is good for us. In the future it helps us also to support IntelliSense when we are writing our views. And, of course, the best thing is, we don’t have to use view data collection that is not error-prone.


Leave a Reply

Your email address will not be published. Required fields are marked *