Sunteți pe pagina 1din 16

ASP.

NET MVC 3 Razor


Version: 1.1.0

Description
ASP.NET MVC 3 introduces the new view engine Razor, which was conceived to simplify the current syntax used in ASP.NET web pages. In this lab you will learn how to create Razor views inside an MVC solution. In the beginning of this Lab you will first get familiar with Razor syntax and its features: general rules, code blocks, inline HTML and layout pages. Once you have learned the basics, in Exercise 2 you will add Razor views in the MVC Music Store solution to provide the same functionality you have in ASP.NET views, but with a clearer and reduced code.At the end of this lab, in Exercise 3, you will learn how to create and consume third party Razor Helpers.

Overview
Note: This Hands-on Lab assumes you have basic knowledge of ASP.NET MVC. If you have not used ASP.NET MVC before, we recommend you to go over ASP.NET MVC Fundamentals Hand-on Lab. ASP.NET MVC 3 introduces the new view engine Razor, which was conceived to simplify the current syntax used in ASP.NET web pages. In this lab, you will learn how to create Razor views inside an MVC solution. In the beginning of this Lab you will first get familiar with Razor syntax and its features: general rules, code blocks, inline HTML and layout pages. Once you have learned the basics, in Exercise 2 you will add Razor views in the MVC Music Store solution to provide the same functionality you have in ASP.NET views, but with a clearer and reduced code. At the end of this lab, in Exercise 3, you will learn how to create and consume Razor Helpers to use images, grids and custom functionality.

About Razor View Engine


Many ASP.NET Web pages have C# or VB code blocks in the same place as HTML markup. In some occasions this combination is uncomfortable for writing and delimiting code. To deal with that problem, Razor was designed as an easy to learn, compact and expressive view engine that enables a fluid coding workflow. Razor is not a new programming language itself, but uses C# or Visual Basic syntax for having code inside a page without ASP.NET delimiter: <%= %>. Razor file extension is cshtml for C# language, and vbhtml for Visual Basic.

Razor Syntax The fundamentals


Before getting introduced to Razor you should first know some simple rules that will help you understand how to write HTML with C# or Visual Basic in the same page: 1. 1. @ is the magic character that precedes code instructions in the following contexts: @ For a single code line/values: A single code line inside the markup: cshtml

<p> Current time is: @DateTime.Now </p>


vbhtml

<p> Current time is: @DateTime.Now </p>


2. @{ } For code blocks with multiple lines: cshtml

@{ var name = John; var nameMessage = "Hello, my name is " + name + " Smith";

}
vbhtml

@Code Dim name = John Dim nameMessage = "Hello, my name is " + name + " Smith" End Code
3. @: For single plain text to be rendered in the page. cshtml

@{ @:The day is: @DateTime.Now.DayOfWeek. It is a <b>great</b> day! }


vbhtml

@Code @:The day is: @DateTime.Now.DayOfWeek. It is a <b>great</b> day! End Code


2. HTML markup lines can be included at any part of the code: It is no need to open or close code blocks to write HTML inside a page. If you want to add a code instruction inside HTML, you will need to use @ before the code: cshtml

@if(IsPost) { <p>Hello, the time is @DateTime.Now and this page is a postback!</p> } else { <p>Hello, today is: </p> @DateTime.Now }
vbhtml

@If IsPost Then @<p>Hello, the time is @DateTime.Now and this page is a postback!</p> Else @<p>Hello, today is: </p> @DateTime.Now End If
3. Razor uses code syntax to infer indent: Razor Parser infers code ending by reading the opening and the closing characters or HTML elements. In consequence, the use of openings { and closings } is mandatory, even for single line instructions: cshtml

// This wont work in Razor. Content has to be wrapped between { } if( i < 1 ) int myVar=0;
vbhtml

// This wont work in Razor. Content has to be wrapped between { } If i < 1 Then Dim myVar As int =0 End if

Conditionals and loops with inline HTML


Here you will find examples of conditionals with inline html.

If statement: cshtml

<p>Single line If</p> @if(result != ""){ <p>Result: @result</p> }


vbhtml

<p>Single line If</p> @If result <> "" Then @<p>Result: @result</p> End If
cshtml

<p>Code block If</p> @{ var showToday = false; if(showToday){ @DateTime.Today; } else{ <text>Sorry!</text> } }
vbhtml

<p>Code block If</p> @Code Dim showToday = false If showToday Then @DateTime.Today Else @<text>Sorry!</text> End if End Code
Foreach statement: cshtml

<p> Single Line Foreach </p> <ul> @foreach (var myItem in Request.ServerVariables){ <li>@myItem</li> } </ul>
vbhtml

<p> Single Line Foreach </p> <ul> @For Each myItem in Request.ServerVariables @<li>@myItem</li> Next myItem </ul>
cshtml

<p> Code block Foreach </p> @{ <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"}; foreach (var person in teamMembers) { <p>@person</p> } }
vbhtml

<p> Code block Foreach </p> @Code @<h3>Team Members</h3> Dim teamMembers() As String = {"Matt", "Joanne", "Robert", "Nancy"} For Each person in teamMembers @<p>@person</p> Next person End Code
While statement: cshtml

@{ var countNum = 0; while (countNum < 50) { countNum += 1; <p>Line #@countNum: </p> } }
vbhtml

@Code Dim countNum = 0 Do While countNum < 50 countNum += 1 @<p>Line #@countNum: </p> Loop End Code

Comments
Comments in Razor are delimited by @**@. If you are inside a C# code block, you can also use // and /* */ comment delimiters. cshtml

@* A Razor Comment *@ @{ //A C# comment /* A Multi line C# comment */ }


vbhtml

@* A Razor Comment *@ @Code //A C# comment /* A Multi line C# comment */ End Code
In this Hands-on Lab, you will learn how to:

Create Razor Layout page templates Create MVC Views using Razor syntax Create and consume Razor Helpers

System Requirements
You must have the following items to complete this lab:

ASP.NET and ASP.NET MVC 3 Visual Studio 2010 Express SQL Server Database (Express edition or above) Note: You can install the previous system requirements by using the Web Platform Installer 3.0:http://go.microsoft.com/fwlink/?LinkID=194638.

Exercises
This Hands-On Lab is comprised by the following exercises: 1. 2. 3. Exercise 1: Creating a Home page view using Razor syntax Exercise 2: Using Models in Razor views Exercise 3: Creating and Consuming Razor Helpers from a View Estimated time to complete this lab: 30 minutes.

Model View Controller: History, theory and usage

Recently I have been fascinated with how to structure web-applications, especially web-applications that use a lot of JavaScript. To learn more I have done some research into one of the most widely used designpatterns:Model-View-Controller (MVC). This blog post explores how MVC is used inSmalltalk, Ruby On Rails, .Net and Cocoa. I also implement Smalltalk's and Cocoa's MVC patterns using jQuery and CoffeeScript.

The history of MVC


MVC is really old and was first described in 1979 by Trygve Reenskaug, then working on Smalltalk at Xerox PARC. Being over 30 years ago does not mean it's dead, far from it... Today MVC is used in most modern web and GUI frameworks, including:

Ruby On Rails: A popular Ruby web-framework Apple Cocoa: Apple's framework for developing Mac OS and iOS applications ASP.Net Framework: Microsoft's web-framework for implementing web applications

Apache Struts: A popular Java web-framework ... And many many more languages and frameworks

The main objectives of MVC


Model-View-Controller as the name applies considers three roles:

Model: manages the behavior and data of the application domain View: represents the display of the model in the UI Controller: takes user input, manipulates the model and causes the view to update There isn't a standard definition of the MVC pattern and many frameworks use a slightly different version. This said there is a core idea of what MVC tries to achieve:

Separating the presentation from the model: Enables implementation of different UIs and better testability Separating the controller from the view: Most useful with web interfaces and not commonly used in GUI frameworks In most implementations the separation between the model and the view is most important. Martin Fowler's notes following interesting thing about Smalltalk's original MVC pattern [in his book Patterns of Enterprise Application Architecture]: The irony is that almost every version of Smalltalk didn't actually make a view/controller separation. To make things more clear let's take a look at how the MVC pattern is implemented across different programming languages and frameworks.

Smalltalk MVC
The first implementation of the MVC pattern was found in Smalltalk-80 - a programming language released in 1980. Smalltalk is a pure object oriented programming language that's very interactive and MVC was one of the core features of the implementation. The main objective of using MVC in Smalltalk was separating the application logic from the user interface - - enabling reuse of the model to implement several user interfaces:

Smalltalk's dependency between model, view and controller:

Things to note about Smalltalk's dependency structure:

The model does not depend on the view or the controller Observer pattern was used to update views when models changed Smalltalk-80 MVC did not make a view/controller separation

Ruby On Rails MVC


Ruby on Rails is a very popular Ruby web-framework that uses MVC.

The client-server environment of web-applications makes things more complicated than the original environment that MVC was invented in. This is mostly because the view can't easily observe the model (at least not without Ajax or Comet communication). Overview of Rails MVC:

Things to note about Rails MVC:

It's a lot different from the original Smalltalk MVC pattern since Rails operates in a very different environment than a typical Smalltalk application The model does not depend on the view or the controller There isn't a direct dependency between the view and the model. The controller collects all the needed data from the model and passes it to the view Given that Rails operates in a client-server environment the view does not update automatically when the model changes Most of today's MVC web-frameworks use a pattern very similar to the one Rails uses

Cocoa MVC
Apple's Cocoa framework is used to create Mac OS X and iOS applications. Cocoa uses a lot of design patterns and MVC is one them. Cocoa's MVC puts a lot importance on the controller and this makes it a lot different than the original Smalltalk MVC. A Cocoa controller acts as a mediator between the view and the model [this is commonly known from the Mediator pattern]:

The reason to use the mediator pattern is probably because the data flow is cleaner than the traditional MVC found in Smalltalk, which looks like this:

The above graphics are from Apple's Cocoa Design Patterns. I recommend reading these documents if you want to know more about Cocoa's design.

ASP.Net MVC framework


ASP.Net started off using a pattern called Model-View-Presenter, but this pattern got "replaced" when Microsoft introduced ASP.Net MVC, which implements a similar MVC pattern used in Rails or Django. CodeGuru has a good blog post on MVP vs. MVC and in it there's a good graphic explaining the difference between these two patterns:

Exploring MVC with jQuery and CoffeeScript


I have done some experiments with sample implementation of MVC patterns using jQuery and CoffeeScript. First do note that the idea of using MVC in JavaScript isn't new and there are already some JavaScript frameworks that use this approach:

backbone.js SproutCore In following implementations I will only implement Smalltalk's and Cocoa's MVC patterns. Rails or ASP.Net MVC patterns are done in a backend environment and I don't think it makes sense to use them for clientside code.

What example to implement?


To make things as simple as possible we want to implement a counter button that increases its value when clicked. A simple HTML implementation could look like this:

<button onclick="this.innerHTML = parseInt(this.innerHTML) + 1">1</button>


We are interested to see how the above code could be structured using a MVC pattern.

Following examples will use a lot more code than a simple HTML implementation and this is fully expected. The reason to use MVC isn't to use fewer lines of code, but to structure code so it's easier to reuse, maintain and test.

Implementing Smalltalk's MVC


Smalltalk's MVC did not make a separation between the view and the controller and it used the observer pattern to update the view. Following this philosophy the button example could look like this:

class ModelCounter

constructor: -> @observers = [] @value = 1

increaseValue: (delta) => @value += delta @notifyObservers()

notifyObservers: => obj.notify(this) for obj in @observers

registerObserver: (observer) => @observers.push(observer)

class ViewCounterButton

constructor: (opts) -> @model_counter = opts.model_counter @button_class = opts.button_class or 'button_counter' @model_counter.registerObserver(this)

render: => elm = $("<button class=\"#{@button_class}\"> #{@model_counter.value}</button>") elm.click => @model_counter.increaseValue(1)

return elm

notify: => $("button.#{@button_class}").replaceWith(=> @render())


The above code could be initialized with following code:

$(document).ready( -> model_counter = new ModelCounter() view_counter = new ViewCounterButton('model_counter': model_counter) $('body').append(view_counter.render(), view_counter.render()) ) Implementing Cocoa's MVC
Like noted before Cocoa's MVC pattern uses the Mediator pattern so the controller acts as a mediator between the view and the model. Following this philosophy our button example could look like this:

class ModelCounter

constructor: (@value=1) ->

increaseValue: (delta) => @value += delta

class ControllerCounter

constructor: (opts) -> @model_counter = opts.model_counter @observers = []

getValue: => @model_counter.value

increaseValue: (delta) => @model_counter.increaseValue(delta) @notifyObservers()

notifyObservers: => obj.notify(this) for obj in @observers

registerObserver: (observer) => @observers.push(observer)

class ViewCounterButton

constructor: (opts) -> @controller_counter = opts.controller_counter @button_class = opts.button_class or 'button_counter' @controller_counter.registerObserver(this)

render: => elm = $("<button class=\"#{@button_class}\"> #{@controller_counter.getValue()}</button>") elm.click => @controller_counter.increaseValue(1) return elm

notify: => $("button.#{@button_class}").replaceWith(=> @render())


The above code could be initialized with following code:

$(document).ready( -> model_counter = new ModelCounter() controller_counter = new ControllerCounter('model_counter': model_counter) view_counter = new ViewCounterButton('controller_counter': controller_counter) $('body').append(view_counter.render(), view_counter.render()) )

Conclusion and further reading


Model-View-Controller has lasted over 30 years and is used in most modern GUI-frameworks and webframeworks. It has proven its worth and it's here to stay. I would expect it being used more and more, especially for next-generation JavaScript frameworks. As my examples show, MVC does produce more code than hack-and-slash HTML code and it's not that suitable if you code small web-applications. But it should be very suitable if you want to code large webapplications where maintainability, reuseability and testability are important. I suggest reading following books and posts if you want to dig deeper into the MVC pattern:

Book references
Patterns of Enterprise Application Architecture by Martin Fowler. Especially Chapter 4 (Web presentation)

When I started developing a project in MVC3.0 with Razor (You will find 'What is Razor?' in next coming articles), I got so many doubts. I have searched so many sites and read so many articles to clarify and to get a better solution as per my requirements. Then I decided to write an article in MVC3.0 to clear those doubts. These set of articles explained in a manner that any body can understand what is mvc and how it can be implemented in real time projects.So let us start.
What is MVC?

Modelviewcontroller (MVC) is a software architecture,currently considered an architectural pattern used in software development.
What is Asp.Net MVC?

The Asp.Net MVC is one of the dotnet frameworks to develop web applications.
Why Asp.Net MVC?

The main aim of developing MVC framework is to support pattern-based application development. In other words, the framework was designed to make it easier to implement software design principles and patterns when building web applications.

More over it supports unit tests. Applications developed in MVC are highly testable. Because MVC applications are highly testable, it supports test driven development (TDD). Extensive support for ASP.NET routing, which is a powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs.

Advantages of MVC

The MVC application can be divided into Model, View, Controller-so this makes it easier to manage. It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application. It provides better support for test-driven development (TDD).

History of MVC

The MVC pattern was invented by Trygve Reenskaug. His first paper was published in 1978 on MVC. It was popularized for use on the web with the advent of Ruby on Rails in 2003. Asp.Net MVC: In 2009, MVC 1.0 was released. In 2010, MVC 2.0 was released. In 2011, MVC 3.0 released.
The MVC Pattern

An MVC application can be divided into three parts:

Model: A model contains application logic. For example in stock management system, the model represents stocks, orders, purchases etc. i.e this consists all the application validation logic, business logic and data access logic. View: In simple terms, it is a visual representation of model. A view contains HTML markup and view logic. Controller: A controller process incoming requests, and performs operations in model, and renders a view or redirects to other view. A controller works as a mediator between a model and a view. In Asp.net MVC, controllers are c# classess and are derived from System.Web.Mvc.Controller class.
What is new in Asp.Net MVC 3.0?

Razor view engine is the major change in MVC3 version. Previous view engines are based on Asp.Net view engine, which depends on the Asp.Net < % and % > blocks. The razor view engine replaced these blocks with @

character.The new notation is quicker to write and faster to compile than the old view engine. It also has more flexible features and allows for better unit testing. The other new features are:

Extensible Scaffolding with MvcScaffold integration HTML 5 enabled project templates Support for Multiple View Engines Controller Improvements JavaScript and Ajax Model Validation Improvements Dependency Injection Improvements and some other New Features...

The examples under these articles are used with razor view engine. Because Microsoft team has made it clear that razor is the future of MVC. In next article we will see how to begin a new MVC 3.0 Razor application. Comments/Suggestions are invited. Happy coding......!

Some differences between ASP.Net MVC 3.0 and ASP.Net MVC 2.0
ASP.Net MVC, first released around year 2009, has evolved to 3.0 (as I am writing this article, 4.0 is on the way). As the history proved, any Microsoft technologies, tools, which upgrade to 3.0, are worth to take a serious look. I would like to introduce some differences between MVC 3 and 2: 1. ASP.Net view engine is changed to Razor. One of the direct effects is: the ASP.Net notation (<% %>) is changed to new notation @. 2. Master page is gone. Well..., not really. It is re-invented as layout page, e.g. _Layout.cshtml. 3. Induced a new feature ViewBag to pass parameter from controller to view. 4. Better support to dependency injection. 5. Better support to JQuery Above items are only from practice point of view. If you want to get the full list of new features of MVC 3.0, please read ASP.Net MVC 3.0 document.

S-ar putea să vă placă și