Click here to Skip to main content
15,860,844 members
Articles / Web Development / ASP.NET

ASP.NET, MVC 3, the Razor View Engine and Google Maps

Rate me:
Please Sign up or sign in to vote.
4.89/5 (19 votes)
26 Jan 2011CPOL7 min read 291.5K   82   53
A quick walk-through of getting Google Maps running in MVC 3 with the Razor View Engine

Introduction

With the release of MVC 3, the updated project templates and the Razor view engine, I wanted to see how hard it would be to get a quick mash-up of some ASP.NET goodness and the Google Maps API.

RazorMaps/title.png

For this project, we're going to walkthrough creating a new project in ASP.NET using MVC 3 in Visual Studio 2010 then Razor-ify a very basic Google Map with a little bit of JavaScript.

Background

Though I touch lightly on some of the concepts of the MVC Framework in this article, for the most part I'll assume that you are comfortable with the pattern. Here are the bits you'll need to follow along:

How Things Have Changed

The Razor view engine is part of a new rendering framework for ASP.NET web pages. Unlike the classic ASP.NET rendering engine which uses opening and closing brackets to denote code (<% %>), Razor allows a cleaner, implied syntax for determining where code blocks start and end.

In the classic renderer in ASP.NET, where you'd see something like this:

ASP.NET
<ul>
<% foreach (var userTicket in Model)
  { %>
    <li><%: userTicket.Value %></li>
<%  } %>
</ul> 

...you'd see something more akin to this in Razor:

ASP.NET
<ul>
@foreach (var userTicket in Model)
{
  <li>@userTicket.Value</li>
}
</ul>  

There are also many other features that streamline development, such as Sections, Layouts and Razor-specific helpers. We'll explore those at a high level in this article.

MVC 3 Tooling Changes

Obviously with the new syntax comes changes to the way the templates are rendered. The tools have been updated accordingly and as a result we see much cleaner view sources when generating our views from the controller. For a view that's not strongly-typed, this is all we need to make the page tick:

RazorMaps/clean-view.PNG

Model inheritance is also significantly simplified and much more human readable. The way we've been doing it since MVC came out:

ASP.NET
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<Sample.Aspclassic.Models.StringModel>" %> 

...and now in Razor:

ASP.NET
@model IEnumerable<RazorMaps.Models.StringModel>
@{ ViewBag.Title = ""; }

We'll have a closer look at some of these features throughout the remainder of this text.

Getting Started

Once installed, it’s fairly easy to invoke the New Project dialog and select ASP.NET MVC 3 Web Application from the Web templates. If you don’t see the project type listed, make sure that you are targeting the correct framework.

RazorMaps/image_14_.png

I named my project RazorMaps. When we click ok, we are then presented with a bit of a wizard to select our options for the project. This is a simple but good improvement over the previous MVC bits because it rolls up the wizard, test project creation and multiple templates (empty versus the “internet application”) and lets us select the view engine.

RazorMaps/image_13_.png

For simplicity sake here, I’ve just selected an Empty template and no test project.

Most of the project pieces feel familiar, in fact, there’s no noticeable changes to the MVC project at a root level and all the expected folders are there.

It’s nice to see that jQuery is added by default to the _layout.cshtml file, and to see that jQuery UI is included in the project.

As of my writing this, it’s also the latest bits for the jQuery library, and they have the vsdoc file updated (Sweet! No more renaming the old one and replacing the library!), and there are other libraries in the mix as well (enabling unobtrusive validation, etc.).

First, A Primer

You can skip to the next section if you are more interested in seeing it run than how it runs, but there are a couple of things that should be pointed out here, so that you're following along.

Razor has a minimal effect on the overall flow of an MVC application. Consider the juicy details of what is going on when a request is made to your app:

  • Receive first request for the application
  • Perform routing
  • Create MVC request handler
  • Create controller
  • Execute controller
  • Invoke action
  • Execute result

from MSDN's Understanding MVC Application Execution

Basically, Razor kicks in at Execute result. Rather than using MasterPages for the template, Razor uses Layouts. Layouts, in the same vain as the syntax, are a simpler, cleaner way to put a template together for a web page. You need only to create an MVC application using each of the view engines to see this. Layouts also tend to read as more active in the rendering process; whereas in a MasterPage, you would put in a ContentSection to specify when content might be rendered, in a Layout you make a call to RenderSection(). Likewise, the sections are defined more like function calls in the content pages. We'll look at these differences as we implement the map.

Another difference is the way in which we look at PartialViews. Razor uses the same file type, .cshtml, for partials and full views, whereas the classic MVC view engine used .ascx (user controls) to implement them. I don't suppose this is significant and there was no real reason to have to carry forth the old distinction.

One downside in the current tooling is that we lose Intellisense on styles and scripts in our views when we've specified JavaScript or CSS sources in our layouts. You can work around this by adding the references to each page (and there are a number of ways to avoid duplicate references if doing this).

So, with a little bit of background on some of the changes and where Razor fits in our paradigm, off we go!

A Simple Home Page

We need to get a view set up so that we have something to look at. The base project doesn't include the controller or the view we're going to want, so we'll start there.

Right-click on Controllers, Add > Controller and name it HomeController. We get our basic controller up-and-running and the code for our first ActionResult (which will invoke the rendering of our home page) is free:

RazorMaps/image_31_.png

Next, right-click anywhere in the Index method and select Add View from the context menu. If the View Name is Index, then you shouldn’t need to change anything else. We’re using the Razor view engine and we already have our layout specified in _viewstart.

RazorMaps/image_30_.png

Press F5 to see your lovely work!

Hello, Google Maps

We have a couple of things that we need to do to get the basic, no-frills map up-and-running. Though I worked from the simple tutorial on the Google Maps Javascript API page, I’m going to try to MVC this up as much as possible and look at some of the features of the Razor view engine.

We know that we need to add the Google Maps script to our page, and we can see from the tutorial that you also need to have a couple of styles. Because we are using layouts in Razor and don’t want these on every page we create, we’ll take advantage of Razor Sections in our layout.

Open up _Layout.cshtml and add the following lines of code to the <head> portion of the document:

ASP.NET
<pre lang="aspnet">@RenderSection("Scripts", false)
<style type="text/css"> 
    @RenderSection("Styles", false)
</style>

We’re adding two optional RenderSections here. This is very similar to creating content sections when using master pages.

Next, pop back into our index.cshtml file so that we can add the juicy bits to get the map loading. At this point, it's worth grabbing one of those cookies.

Fleshing Out the Page

Right at the top of the file, you’re going to want to add the following code:

ASP.NET
@{ 
    ViewBag.Title = "MVC 3 and Google Maps"; 
} 
@section Scripts { 
    <script type="text/javascript" 
	src="http://maps.google.com/maps/api/js?sensor=false"></script> 
} 
@section Styles { 
    html { height: 100% } 
    body { height: 100%; margin: 0px; padding: 0px } 
    #map_canvas { height: 80% } 
} 

The ViewBag is a dynamic expression that gets evaluated at runtime. The "Title" property is filled into our layout template with the @ViewBag.Title expression.

Next, we have our two sections; the first adds the map script to our page, the second applies and specifies the styles we need to get the map rendering correctly.

The rest of the page consists of:

  • A div element (to host the map)
  • An initialize function that sets up the map, and
  • A jQuery shortcut to invoke the initialize function when the page is ready

Here’s the code:

ASP.NET
<h2>Hello, Google Maps</h2>
<div id="map_canvas" style="width:80%; height:80%"></div>
<script type="text/javascript">
    function initialize() { 
        var latlng = new google.maps.LatLng(40.716948, -74.003563); 
        var options = { zoom: 14, center: latlng, 
		mapTypeId: google.maps.MapTypeId.ROADMAP}; 
        var map = new google.maps.Map(document.getElementById
			("map_canvas"), options); 
    }
    $(function () { 
        initialize(); 
    }); 
    
</script> 

And there you have it! Press F5 again and the map loads.

Conclusion

If you have a good handle on ASP.NET MVC and you understand MasterPages, the switch to the Razor engine and templates is going to be easy and refreshing. Integrating per-page code, via Razor section rendering, is straightforward and keeps our templates clean.

Updated script libraries and improved templates and a ton of feature enhancements round out this release nicely.

Here are some links and helpful references to get you plugged in to related content:

History

  • 2011-01-21.1: First version
  • 2011-01-21.2: Uploaded application image
  • 2011-01-21.3: Added Google Maps link
  • 2011-01-21.4: Added more background on Razor (thanks Pete!)
  • 2011-01-21.5: Added more information on tooling
  • 2011-01-26.1: Added primer, MSDN link in references

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Canada Canada
For almost 30 years I have been working with computers, learning a myriad of languages and participating in various computing environments.

Though I have been mentoring other developers for the last decade, I have recently found a strong interest in writing and am learning to translate the fun of in-person teaching to something I can get into article form.

I enjoy following technology trends, new gadgets and trying to guess where innovation will lead us next (I'm kinda holding out for a robot-served utopia, but willing to submit to our future robot leaders).

I am a guy who is passionate about my faith, my family and a cure for Juvenile Diabetes (my son lives with this disease).

Comments and Discussions

 
QuestionGoogle Map is not rendering in my razor Pin
Paris Pantigoso31-Mar-16 13:14
professionalParis Pantigoso31-Mar-16 13:14 
Questionnot working with me Pin
Member 1071873311-Jun-14 11:51
Member 1071873311-Jun-14 11:51 
AnswerRe: not working with me Pin
Paris Pantigoso31-Mar-16 13:28
professionalParis Pantigoso31-Mar-16 13:28 
Suggestionthis does not work in mvc 4 until you do these things... Pin
EntilzhaFini2-Jun-13 18:03
EntilzhaFini2-Jun-13 18:03 
GeneralRe: this does not work in mvc 4 until you do these things... Pin
Paris Pantigoso31-Mar-16 13:30
professionalParis Pantigoso31-Mar-16 13:30 
GeneralRe: this does not work in mvc 4 until you do these things... Pin
EntilzhaFini8-Jun-16 6:50
EntilzhaFini8-Jun-16 6:50 
GeneralRe: this does not work in mvc 4 until you do these things... Pin
Paris Pantigoso8-Jun-16 8:05
professionalParis Pantigoso8-Jun-16 8:05 
Generalplease i need to display the different locations of the clients on map with info window in mvc Pin
Anil from Bombay30-Jul-12 20:29
Anil from Bombay30-Jul-12 20:29 
QuestionVote is 5 Pin
Luck)5-Jul-12 9:50
Luck)5-Jul-12 9:50 
QuestionNice Job! Pin
Your Display Name Here23-May-12 18:15
Your Display Name Here23-May-12 18:15 
AnswerRe: Nice Job! Pin
TheyCallMeMrJames24-May-12 6:04
TheyCallMeMrJames24-May-12 6:04 
QuestionGuidance on "not unloading" a view Pin
salsafreakpr24-Jan-12 6:08
salsafreakpr24-Jan-12 6:08 
QuestionVersion of map Pin
kaneXtreme12-Jan-12 3:34
kaneXtreme12-Jan-12 3:34 
AnswerRe: Version of map Pin
TheyCallMeMrJames12-Jan-12 7:07
TheyCallMeMrJames12-Jan-12 7:07 
SuggestionLayouts, in the same vain as the syntax, Pin
Setiri30-Aug-11 19:42
Setiri30-Aug-11 19:42 
QuestionProblem Running Code Pin
xiecsuk29-Jul-11 0:34
xiecsuk29-Jul-11 0:34 
AnswerRe: Problem Running Code Pin
TheyCallMeMrJames2-Aug-11 5:57
TheyCallMeMrJames2-Aug-11 5:57 
GeneralRe: Problem Running Code Pin
xiecsuk2-Aug-11 22:09
xiecsuk2-Aug-11 22:09 
GeneralRe: Problem Running Code Pin
TheyCallMeMrJames3-Aug-11 5:03
TheyCallMeMrJames3-Aug-11 5:03 
GeneralRe: Problem Running Code Pin
xiecsuk3-Aug-11 23:28
xiecsuk3-Aug-11 23:28 
GeneralRe: Problem Running Code Pin
TheyCallMeMrJames4-Aug-11 3:20
TheyCallMeMrJames4-Aug-11 3:20 
QuestionUsing this with JQuery Mobile Pin
Member 471957128-Jun-11 7:25
Member 471957128-Jun-11 7:25 
AnswerRe: Using this with JQuery Mobile Pin
Member 471957128-Jun-11 8:11
Member 471957128-Jun-11 8:11 
GeneralRe: Using this with JQuery Mobile Pin
TheyCallMeMrJames28-Jun-11 8:39
TheyCallMeMrJames28-Jun-11 8:39 
GeneralMy vote of 5 Pin
aeonjake20-Jun-11 18:49
aeonjake20-Jun-11 18:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.