Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

October 2010 - Posts

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.

Source code

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

Source code @ GitHub Source code repository
GitHub

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

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.


@model Experiments.AspNetMvc3NewFeatures.Razor.Models.ContentPage

And in the browser our view looks like this.

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

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.

Posted: Oct 13 2010, 07:15 PM by DigiMortal | with 11 comment(s)
Filed under: , ,
ASP.NET MVC 3 Beta: View start files for Razor view engine

To follow better DRY (Don’t Repeat Yourself) principle Razor views support now defaults that are applied to all views in ASP.NET MVC web application. Default can be applied by special file so you have one place where everything common is defined. In this posting I will show you how defaults work and how to use them.

View start files

ASP.NET MVC 3 Beta: View start file in Razor

If you create new ASP.NET MVC 3 Beta web application you will find there file called _ViewStart.cshtml. In VB.NET projects this file is called _ViewStart.vbhtml.

By default this file is very short and simple containing only definition for layout page (ASPX synonym for layout page is master page). This page is run before the code of requested view is run.

_ViewStart.cshtml has also scope – it works for views that are located under the folder where _ViewStart.cshtml is. Views in other folders (by example views in other areas if you are using areas) are not affected by  _ViewStart.cshtml in /Views/ folder.

Image on right shows how _ViewStart.cshtml is located in default internet application project. By example, it covers all views in Home and Shared folder but not views that have restricted access (_Layout.cshtml cannot be accessed directly).

Of course, we can add more functionality to _ViewStart.cshtml if we need but you have to be sure that this is something that cannot be easily done using layout pages and this is something that must be applied to views.

ASP.NET MVC 3 Beta: Caching charts

In my previous posting about charts in ASP.NET MVC 3 I gave you basic idea about how to use them. In this posting I will show you something cool – we will optimize performance of our application by caching charts so we don’t have to generate them on every request.

Source code

You can find source code of this example from my GitHub repository.

Source code @ GitHub Source code repository
GitHub

Chart example is located in Experiments.AspNetMvc3NewFeatures solution. Project name is Experiments.AspNetMvc3NewFeatures.Razor.

Caching charts

Let’s starts with example form previous posting where cache was not used.


public ActionResult MyChart()
{
    var model = new ChartModel();
    var data = model.GetChartData();
 
    new Chart(400, 200, ChartTheme.Blue)
        .AddTitle("Price enquiries")
        .DataBindTable(data, "X")
        .Write("png");
 
    return null;
}

I added cache example as different action to my application to illustrate that cache support can be added using only couple of lines of code. Take a look at this code.


public ActionResult MyCachedChart()
{
    const string chartKey = "MyCachedChart";
    var chart = Chart.GetFromCache(chartKey);
 
    if (chart == null)
    {
        var model = new ChartModel();
        var data = model.GetChartData();
 
        chart = new Chart(400, 200, ChartTheme.Blue)
                .AddTitle("Chart cached: " + DateTime.Now)
                .DataBindTable(data, "X");
        chart.SaveToCache(chartKey,1,false);
    }
 
    chart.Write("png");
    return null;
}

We use constant key when dealing with cache. If we get chart from cache then we use the cached version. If there is no cached version we will create new chart, bind it to data and cache the instance. In this code chart is saved to cache for one minute. After that cache expires.

Application with two charts

And here is the result of our work. You can test caching by refreshing the page and reading the title of second chart. The title changes after cache timeout that is 1 minute in our application.

aspnet-mvc3-cached-chart

Although upper chart does not change it is created again and again for every request.

Conclusion

We took code example from my previous posting and added couple of lines of code to it so our charts are cached for one minute. It was extremely simple change that took no markable amount of our time. You can change the cache timeout and you can also turn on sliding expiration if it fits to your scenario better – just modify the last two parameters of WriteToCache() method.

ASP.NET MVC 3 Beta: Built-in support for charts

ASP.NET MVC does not have built-in support for chart control and that’s why I worked out my own solution to make ASP.NET MVC support chart control. With ASP.NET MVC 3 we will get official support for charts right out of the box. In this posting I will show you how to use charts in ASP.NET MVC 3 Beta.

ASP.NET MVC 3 has cool support for charts. We have to create charts in our code or define them using XML. We have nice Chart class that offers us pretty cool fluent interface that is convenient to use. But let’s get started.

Source code

If you want to play with my solution then please feel free to download source code from my source code repository in GitHub.

Source code @ GitHub Source code repository
GitHub

Chart example is located inExperiments.AspNetMvc3NewFeatures solution. Project name is Experiments.AspNetMvc3NewFeatures.Razor. 

Page with chart

As a first thing we need a view where we show chart. Our view is simple and it contains only one image that is loaded from request made to controller.


@{
    View.Title = "Home Page";
}
 
<h2>@View.Message</h2>
<p>
    <img src="/Home/Chart" />
</p>

This page is index view of home controller. I just removed the welcome message and added img tag.

Displaying chart

Chart image is returned by controller action Chart(). In this action we will ask data from model and give it to view. We are using view here because I want to illustrate you something you should know.


public ActionResult Chart()
{
    var model = new ChartModel();
    var data = model.GetChartData();
 
    return View(data);
}

Here is my primitive chart model.


public class ChartModel
{
    public IList GetChartData()
    {
        return new ArrayList
        {
             new { X = DateTime.Now.AddMonths(-2), Y = 200 },
             new { X = DateTime.Now.AddMonths(-1), Y = 300 },
             new { X = DateTime.Now, Y = 500 }
       };
    }
}

Chart view

Here is our chart view. All we do in this view is defining chart, giving it a nice look and then displaying it as image.


@model dynamic
 
@{
    View.Title = "Chart";
    Layout = "~/Views/Shared/_Layout.cshtml";
 
    var key = new Chart(400, 200, ChartTheme.Blue)
                .AddTitle("Price enquiries")
                .DataBindTable(Model, "X")
                .Write("png");
}

When we run our application we can see that chart is rendered correctly. We can also add some mark-up to view but still everything works. Write() method is the evil here. It guarantees that response contains only the image of chart with all headers needed and nothing more. Seems like we don’t need view here.

Let’s output the image in controller action and remove view.


public ActionResult Chart()
{
    var model = new ChartModel();
    var data = model.GetChartData();
 
    new Chart(400, 200, ChartTheme.Blue)
        .AddTitle("Price enquiries")
        .DataBindTable(data, "X")
        .Write("png");
 
    return null;
}

I think this solution is better because we have not so much code and therefore we don’t really have a point to split part of this short code to view. Also we have one file less in our project now.

Our first ASP.NET MVC chart

When you run the code you should see something like this in browser window. This nice blue design is not my own work that I don’t want you to tell about. I used ChartTheme.Blue when instantiating Chart and this is the way I can tell to chart what kind of theme to use.

ASP.NET MVC 3: Charting with Razor

Okay, my chart looks very nice to me!

Conclusion

Charting is made very convenient in ASP.NET MVC 3 Beta. We can use Chart class that has good API with fluent syntax and it is extremely easy to use. To make chart look nice and cool we used built-in theme. We used no hacks bridging ASP.NET Forms and ASP.NET MVC frameworks and our code is simple and clean.

NuPack, ASP.NET MVC 3 Beta and WebMatrix Beta 2 are here!

Some great news from Microsoft dudes – NuPack, ASP.NET MVC 3 Beta and WebMatrix Beta 2 are here! Seems like busy weekend is coming. Here you can find download links to new versions of products.

Download links

You can find more information and references from ScottGu’s blog posting Announcing NuPack, ASP.NET MVC 3 Beta, and WebMatrix Beta 2. For NuPack there is good introduction by Scott Hanselman Introducing NuPack Package Management for .NET - Another piece of the Web Stack.

More Posts « Previous page