Documente Academic
Documente Profesional
Documente Cultură
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.
@{ 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
@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
If statement: cshtml
<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 *@ @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.
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.
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
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:
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
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:
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.
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.
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.
class ModelCounter
class ViewCounterButton
return elm
$(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
class ControllerCounter
class ViewCounterButton
render: => elm = $("<button class=\"#{@button_class}\"> #{@controller_counter.getValue()}</button>") elm.click => @controller_counter.increaseValue(1) return elm
$(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()) )
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
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.