Over a million developers have joined DZone.

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

DZone 's Guide to

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

· ·
Free Resource

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.

Source code

You can find source code for this example from my Visual Studio examples GitHub repository.

Source code @ GitHub Source code repository

The project where Razor is used is called Experiments.AspNetMvc3NewFeatures.Razor.


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;

First line of the view sets type of model.

@model Experiments.AspNetMvc3NewFeatures.Razor.Models.ContentPage

And in the browser our view looks like this.

ASP.NET MVC 3: Strongly-typed view in Razor


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.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}