SlideShare a Scribd company logo
ASP.NET MVC 3 Introduction Twitter: @tomijuhola [email_address] +358 44 033 8639 Tomi Juhola, 14.6.2011 Versio:  |  Status:      |  Päivitetty: 0.1 Luonnos Tomi Juhola, 14.06.2011
Motivation? Target? Needed to do slides about ASP.NET MVC Made promises Hard to find professional ASP.NET MVC developers TARGET: Get you everyone into basic ideas of ASP.NET MVC Make it easy to start developing simple web applications
Agenda ASP.NET WEBFORMS VS. ASP.NET MVC ROUTING  – FROM REQUEST TO FUNCTION CALLS CONTROLLER S  & ACTION S VIEW –  DISPLAYING DATA PASSING DATA
ASP.NET WebForms VS.  ASP.NET MVC 01
ASP.NET WebForms Drag ’n drop GUI programming on web? Abstraction layer Issues: ViewState: Slow, hard to control Page life cycle No actual separation of concerns Very tight architecture (hard to e.g. unit test) No control over HTML
ASP.NET MVC X New model  (ALT.NET):  Dec 2007 ASP.NET MVC CTP March 2009 ASP.NET MVC 1 Rapid development:  March 2010 ASP.NET MVC 2 Jan 2011 ASP.NET MVC 3 Dec 2011 ASP.NET MVC 4?  RTM already out!
ASP.NET MVC benefits Familiar MVC architecture Close to HTTP: Request, update data, provide response Extensible by design Control over HTML & HTTP Testable by design Routing Mature technology beneath (ASP.NET) Modern API (.NET4, LINQ, lambda expr., extension methods etc.) Open source (MS-PL licensed) Convention over configuration
Model – View - Controller Models implement the logic of the application Views display data and present the UI Controllers handle user interactions, work with the models and select next view to display ->  Loose coupling, clear separation of concerns
Project structure App_Data, e.g. resource files Content CSS, images, etc. Controllers, hmm.. The names of all controllers have to end with "Controller" Models, model classes Scripts, script files. By default, contains a bunch of js files. Views, View files like ViewPage (.aspx), ViewUserControl (.ascx), and ViewMasterPage (.master) files.
Routing – from requests to function calls 02
Routing ASP.NET MVC uses standard ASP.NET routing to direct HTTP requests to correct handlers (correct controller's action) Enables use of URLs that don't map to specific files Easier to read URLs Routing also handles automatically url parameter parsing to objects etc. Example route and routing rule: http://server/application/Products/show/beer, the routing parser passes the values Products, show, and beer to the page handler. URL pattern can be e.g. server/application/{area}/{action}/{category}
Registering routes public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // MapRoute parameters: Route name, URL with parameters  // and parameter defaults routes. MapRoute ("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }  ); } protected void Application_Start() { RegisterRoutes (RouteTable.Routes); } }
MVC request handling Order no Stage Details 0 Receive first request for the application In the Global.asax file, Route objects are added to the RouteTable object. 1. Perform routing The UrlRoutingModule module uses the first matching Route object in the RouteTable collection to create the RouteData object, which it then uses to create a RequestContext object. 2. Create MVC request handler The MvcRouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler. 3. Create controller The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object (typically an instance of the DefaultControllerFactory class) to create the controller instance with. 4. Execute controller The MvcHandler instance calls the controller's Execute method. 5. Invoke action For controllers that inherit from the ControllerBase class, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method. 6. Execute result The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The built-in result types that can be executed include the following: ViewResult (which renders a view and is the most-often used result type), RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.
Route default values public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute("Default", "Category/{action}/{categoryName}", New { categoryName= "food", action="show"}); } URL Parameter values /Category action = "show" (default value) categoryName = "food" (default value) /Category/add action = "add" categoryName = "food" (default value) /Category/add/beer action = "add" categoryName= "beverages"
Controllers and actions 03
Controllers and Actions Naming convention: xxxController Requested URLs are mapped to Controller classes and Action methods Base class for all controllers is Controller (and its base is ControllerBase) public class MyController : Controller { public ActionResult HelloWorld() { ViewBag.Message = "Hello World!"; return View(); } }
ActionResult Base class for return values from actions Types (with helper method): ViewResult – Renders a Web page View() PartialViewResult – Renders a partial view PartialView() RedirectResult – Redirects to another URL Redirect() RedirectToRouteResult – Redirects to action RedirectToAction()/-Route() ContentResult – Returns a user def content Content() JsonResult – returns serialized JSON object Json() JavaScriptResult – returns JS script JavaScript() FileResult – Returns binary output File() EmptyResult - Same as null
Non-action methods in Controller [NonAction]   p ublic  void DoSomething()  { //  L ogic.  }
View – displaying data 04
Views Responsible for displaying data HTML & simple code If you’re doing complicated things in Views, you’re probably doing it wrong Convention: View returned by HomeController’s Index Action is \Views\Home\Index.aspx Example View: <%@ Page Language=&quot;C#&quot; MasterPageFile=&quot;/Views/Shared/Site.Master&quot; Inherits=&quot;System.Web.Mvc.ViewPage&quot; %>  <asp:Content ID=&quot;aboutContent&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;> <h2>About</h2>  <p>  P ut content here.   </p>  </asp:Content>
Site master (or _Layout.cshtml in Razor) Can be located from /Views/Shared/Site.Master  (_Layout.cshtml) Used to create common page structure Important parts: In Site.Master:    <asp:ContentPlaceHolder ID=&quot;MainContent&quot; runat=&quot;server&quot; />  In actual pages:  <%@ Page Title= ””  Language=&quot;C# ”  MasterPageFile= ” ~/Views/Shared/Site.Master ”  Inherits= ” System.Web.Mvc.ViewPage< ModelType > ”  %>   Include here: Common scripts CSSs Navigation etc. always visible bars
HTML Helpers Used to create simple HTML elements (styling in CSS) Easy to tie into Models In views usable with following syntax:  <% Html.ActionLink(…) %> Can be extended by extension methods, or own classes can be created Difference between <%: %>, <% %> and <%= %>? Renders with encoding, no rendering, renders withouth encoding Methods in HtmlHelper class ( http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.aspx ) ActionLink, BeginForm, CheckBox, Display, DropDownList, Editor, Hidden, Label, ListBox, Partial, Password, RadioButton, RenderAction, RenderPartial, RouteLink, TextArea, TextBox, ValidationSummary, ValidationMessage etc.
Partial views Used to follow DRY principle (Don’t Repeat Yourself) Used to define a view that can be rendered inside parent view For this ASP.NET user controls are used (.ascx) Essential points: Shares same ViewData & ViewBag as parent Can be also strongly typed Consider these for e.g. basic forms, views etc. for each type you have This way the views & forms are similar in each page
View engines ASP.NET MVC 3 adds also a new view engine: Razor There are others also available: Bellevue, Brail, Hasic, NDjango, NHaml, NVelocity, SharpTiles, Spark, StringTemplate, WingBeats, Xslt See:  http://stackoverflow.com/questions/1451319/asp-net-mvc-view-engine-comparison  and  http://channel9.msdn.com/coding4fun/articles/Developer-Review-Four-ASPNET-MVC-View-Engines   Instead of using <% … %> notation uses plain @ character. E.g. <h3>Hello, <%: name %>! </h3>  vs.  <h3>Hello, @name! </h3> <p>Now: <%: Datetime.Now %>! </p>  vs.  <p>Now: @DateTime.Now</p>
Razor vs. traditional WebEngine Traditional <% if (Model.Value==true)%> <%{>% <%  var outsideTemp = 79; var weatherMsg = &quot;Hello, it is &quot; + outsideTemp + &quot; degrees.&quot;;   %>  <p>Today's weather:  <%:  weatherMsg  %>  </p> <%}%> Razor @if (Model.Value==true) {  @{ var outsideTemp = 79; var weatherMsg = &quot;Hello, it is &quot; + outsideTemp + &quot; degrees.&quot;; } <p>Today's weather: @ weatherMsg </p> }
Passing data 05
Method parameters By default, the parameters are retrieved from the request's data collection Contains name/values pairs for form data, query string values, and cookie values. There are several ways to access URL parameter values in the action methods Request and Response properties Automatically mapped parameters Examples with  /Products/Detail?id=3   (or better  /Products/Detail/3 , remember default routing?) public void Detail()  {  int id = Convert.ToInt32(Request[&quot;id&quot;]);  }  public ResultAction Detail(int id)  {  // Logic (id is already usable here) }
Passing data to view Multiple choices: ViewData:  ViewData[”name”]=”Matti”; ViewBag:  ViewBag.Name = ”Matti”; Model:  var person = new Person(”Matti”); return View(person); --- <%: Model.Name %> View should preferably be strongly typed with view specific model, use that to pass data Simple messages (like ”data updated”) can be handled with ViewBag ViewData is more legacy way of doing this If ViewData is used, use constants, instead of Magic Strings
Strongly typed views & Scaffolding When creating a view you can define the model class for the view Can be also dynamic when the view is not strongly typed Strongly typed views allow also scaffolding of basic views So autogenerated forms, lists, details views etc.
Strongly typed HtmlHelpers Named like: Html.NnnnFor(..) Html.TextBoxFor(..) Html.EditorFor(..) Html(TextAreaFor(..) Usage: <%= Html.LabelFor(model => model.ProductionVersion) %> Uses so called lambda syntax to strongly type the parameters Two kinds of strongly type helpers: Element level: TextBoxFor(), RadioButtonFor() Model level + others: EditorFor(), ValidationMessageFor()
Form handling? Starting a form: <%  using(Html.BeginForm(&quot;HandleForm&quot;, &quot;Home&quot;))  %>  <% { %>  <!-- Form content goes here -->  <% } %>  <%  Html.BeginForm();  %>  <!-- Form content goes here -->  <%  Html.EndForm();  %>  Mapping:   Enter your name: <%= Html.TextBox( ” name ” ) %>  public ActionResult HandleForm(string  name ) {}  Mapping from Form-data: User.Name  = Request.Form[” name” ]; More about forms:  http://msdn.microsoft.com/en-us/library/dd410596.aspx
Easiest way to map? From NerdDinner: public  ActionResult Edit(int  id,  FormCollection formValues ) { Dinner dinner = dinnerRepository.GetDinner(id); UpdateModel(dinner, formValues);  // Automatically updates  dinnerRepository.Save(); return RedirectToAction(&quot;Details&quot;, new {id=dinner.DinnerID }); }
What next? Validation ASP.NET MVC and jQuery Data access in ASP.NET MVC apps Custom HtmlHelpers Unit testing ASP.NET MVC Custom routing Security: XSS, Cross-site request forgery, cookie stealing, error reporting etc. Migration to MVC MVC & Web Forms together? Extending MVC, plugging in own handlers Etc.etc.etc.etc.
Further reading (books for MVC 3 coming soon…) Professional ASP.NET MVC 2 by Jon Galloway, Scott Hanselman, Phil Haack, Scott Guthrie, Rob Conery (Wrox) Pro ASP.NET MVC 2 Framework by Steven Sanderson (Apress) Test-Drive ASP.NET MVC by Jonathan McCracken (Pragmatic bookshelf) ASP.NET MVC 2 in Action by Jeffrey Palermo, Ben Scheirman, Jimmy Bogard etc. (Manning)
Web resources Official MVC site http://www.asp.net/mvc Blogs: http://weblogs.asp.net/scottgu/default.aspx http://haacked.com/ http://www.hanselman.com/blog/ http://blog.maartenballiauw.be/
Example web apps http://nerddinner.codeplex.com/ http://flickrxplorer.codeplex.com/ http://kigg.codeplex.com/ http://codecampserver.codeplex.com/ http://orchardproject.net/ http://cartrackr.codeplex.com/   In MVC 1, anyone care to rewrite it in ASP.NET MVC 3?
www.lindorff.fi Thanks! Tomi Juhola Development Lead Puh: 010 2700 00, Faksi: 010 2700 100 GSM: 044 033 8639 [email_address] www.lindorff.fi Joukahaisenkatu 2 FI-20100 Turku
Ad

More Related Content

What's hot (18)

Devoxx 09 (Belgium)
Devoxx 09 (Belgium)Devoxx 09 (Belgium)
Devoxx 09 (Belgium)
Roger Kitain
 
ASP .net MVC
ASP .net MVCASP .net MVC
ASP .net MVC
Divya Sharma
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
Eric Wise
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
Saurabh Dixit
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
rohitkumar1987in
 
Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009
bturnbull
 
Jsp1
Jsp1Jsp1
Jsp1
Soham Sengupta
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
Barry Gervin
 
29 Jsp
29 Jsp29 Jsp
29 Jsp
DSKUMAR G
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
buildmaster
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
LearnNowOnline
 
07 02-05
07 02-0507 02-05
07 02-05
Nimmanon Lasaku
 
Introduction to Ember.js and how we used it at FlowPro.io
Introduction to Ember.js and how we used it at FlowPro.ioIntroduction to Ember.js and how we used it at FlowPro.io
Introduction to Ember.js and how we used it at FlowPro.io
Paul Knittel
 
Mvc
MvcMvc
Mvc
Furqan Ashraf
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 
Training On Angular Js
Training On Angular JsTraining On Angular Js
Training On Angular Js
Mahima Radhakrishnan
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
Stefano Paluello
 
Devoxx 09 (Belgium)
Devoxx 09 (Belgium)Devoxx 09 (Belgium)
Devoxx 09 (Belgium)
Roger Kitain
 
AngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPIAngularJS Fundamentals + WebAPI
AngularJS Fundamentals + WebAPI
Eric Wise
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan
 
Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009Rails 2.3 and Rack - NHRuby Feb 2009
Rails 2.3 and Rack - NHRuby Feb 2009
bturnbull
 
CTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVCCTTDNUG ASP.NET MVC
CTTDNUG ASP.NET MVC
Barry Gervin
 
ASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp PresentationASP.net MVC CodeCamp Presentation
ASP.net MVC CodeCamp Presentation
buildmaster
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
LearnNowOnline
 
Introduction to Ember.js and how we used it at FlowPro.io
Introduction to Ember.js and how we used it at FlowPro.ioIntroduction to Ember.js and how we used it at FlowPro.io
Introduction to Ember.js and how we used it at FlowPro.io
Paul Knittel
 
Adding a view
Adding a viewAdding a view
Adding a view
Nhan Do
 

Viewers also liked (20)

HTML 5 and CSS 3
HTML 5 and CSS 3HTML 5 and CSS 3
HTML 5 and CSS 3
Kannika Kong
 
Android Basics
Android BasicsAndroid Basics
Android Basics
gauthamns
 
HTML 5 Overview
HTML 5 OverviewHTML 5 Overview
HTML 5 Overview
Vangos Pterneas
 
20121019-HTML5
20121019-HTML520121019-HTML5
20121019-HTML5
Chih-Hsuan Kuo
 
Creating Great Apps with MOTODEV Studio for Android
Creating Great Apps with MOTODEV Studio for AndroidCreating Great Apps with MOTODEV Studio for Android
Creating Great Apps with MOTODEV Studio for Android
Motorola Mobility - MOTODEV
 
Android basics
Android basicsAndroid basics
Android basics
Berglind Ósk Bergsdóttir
 
This Old Website: : Applying HTML5, CSS3, and Responsive Design to An Existin...
This Old Website: : Applying HTML5, CSS3, and Responsive Design to An Existin...This Old Website: : Applying HTML5, CSS3, and Responsive Design to An Existin...
This Old Website: : Applying HTML5, CSS3, and Responsive Design to An Existin...
Wolf Loescher
 
Android basics
Android basicsAndroid basics
Android basics
Ankit Agrawal
 
EDTED SP - HTML 5 e CSS 3 - Junho de 2011
EDTED SP - HTML 5 e CSS 3 - Junho de 2011EDTED SP - HTML 5 e CSS 3 - Junho de 2011
EDTED SP - HTML 5 e CSS 3 - Junho de 2011
Leonardo Balter
 
Urine for a Treat (or: ASP.NET MVC)
Urine for a Treat (or: ASP.NET MVC)Urine for a Treat (or: ASP.NET MVC)
Urine for a Treat (or: ASP.NET MVC)
Joey DeVilla
 
365on Lab Asp.Net MVC Fundamentos 01 Overview
365on Lab Asp.Net MVC Fundamentos 01 Overview365on Lab Asp.Net MVC Fundamentos 01 Overview
365on Lab Asp.Net MVC Fundamentos 01 Overview
Alexsandro Almeida
 
Pertemuan 3 pm
Pertemuan 3   pmPertemuan 3   pm
Pertemuan 3 pm
obanganggara
 
Android
AndroidAndroid
Android
lahiru7
 
【第一季第五期】要漂亮很容易!——超简单CSS速成教程
【第一季第五期】要漂亮很容易!——超简单CSS速成教程【第一季第五期】要漂亮很容易!——超简单CSS速成教程
【第一季第五期】要漂亮很容易!——超简单CSS速成教程
tbosstraining
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
Rakshak R.Hegde
 
Mono for Android Development
Mono for Android DevelopmentMono for Android Development
Mono for Android Development
Thinslices
 
android basics
android basicsandroid basics
android basics
sudhir saurav
 
Android Applications Introduction
Android Applications IntroductionAndroid Applications Introduction
Android Applications Introduction
Anjali Rao
 
Web设计 5 “动感新势力”(css3 html5 以及 web_gl)
Web设计 5 “动感新势力”(css3 html5 以及 web_gl)Web设计 5 “动感新势力”(css3 html5 以及 web_gl)
Web设计 5 “动感新势力”(css3 html5 以及 web_gl)
ziggear
 
Android development - the basics, FI MUNI, 2012
Android development - the basics, FI MUNI, 2012Android development - the basics, FI MUNI, 2012
Android development - the basics, FI MUNI, 2012
Tomáš Kypta
 
Android Basics
Android BasicsAndroid Basics
Android Basics
gauthamns
 
Creating Great Apps with MOTODEV Studio for Android
Creating Great Apps with MOTODEV Studio for AndroidCreating Great Apps with MOTODEV Studio for Android
Creating Great Apps with MOTODEV Studio for Android
Motorola Mobility - MOTODEV
 
This Old Website: : Applying HTML5, CSS3, and Responsive Design to An Existin...
This Old Website: : Applying HTML5, CSS3, and Responsive Design to An Existin...This Old Website: : Applying HTML5, CSS3, and Responsive Design to An Existin...
This Old Website: : Applying HTML5, CSS3, and Responsive Design to An Existin...
Wolf Loescher
 
EDTED SP - HTML 5 e CSS 3 - Junho de 2011
EDTED SP - HTML 5 e CSS 3 - Junho de 2011EDTED SP - HTML 5 e CSS 3 - Junho de 2011
EDTED SP - HTML 5 e CSS 3 - Junho de 2011
Leonardo Balter
 
Urine for a Treat (or: ASP.NET MVC)
Urine for a Treat (or: ASP.NET MVC)Urine for a Treat (or: ASP.NET MVC)
Urine for a Treat (or: ASP.NET MVC)
Joey DeVilla
 
365on Lab Asp.Net MVC Fundamentos 01 Overview
365on Lab Asp.Net MVC Fundamentos 01 Overview365on Lab Asp.Net MVC Fundamentos 01 Overview
365on Lab Asp.Net MVC Fundamentos 01 Overview
Alexsandro Almeida
 
【第一季第五期】要漂亮很容易!——超简单CSS速成教程
【第一季第五期】要漂亮很容易!——超简单CSS速成教程【第一季第五期】要漂亮很容易!——超简单CSS速成教程
【第一季第五期】要漂亮很容易!——超简单CSS速成教程
tbosstraining
 
Mono for Android Development
Mono for Android DevelopmentMono for Android Development
Mono for Android Development
Thinslices
 
Android Applications Introduction
Android Applications IntroductionAndroid Applications Introduction
Android Applications Introduction
Anjali Rao
 
Web设计 5 “动感新势力”(css3 html5 以及 web_gl)
Web设计 5 “动感新势力”(css3 html5 以及 web_gl)Web设计 5 “动感新势力”(css3 html5 以及 web_gl)
Web设计 5 “动感新势力”(css3 html5 以及 web_gl)
ziggear
 
Android development - the basics, FI MUNI, 2012
Android development - the basics, FI MUNI, 2012Android development - the basics, FI MUNI, 2012
Android development - the basics, FI MUNI, 2012
Tomáš Kypta
 
Ad

Similar to ASP.NET MVC introduction (20)

Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
Volkan Uzun
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Maarten Balliauw
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
yuvalb
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
micham
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
nspyre_net
 
ASP.NET MVC
ASP.NET MVCASP.NET MVC
ASP.NET MVC
Paul Stovell
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company india
Jignesh Aakoliya
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
Phuc Le Cong
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
ASP.NET 3.5 SP1 (VSLive San Francisco 2009)
ASP.NET 3.5 SP1 (VSLive San Francisco 2009)ASP.NET 3.5 SP1 (VSLive San Francisco 2009)
ASP.NET 3.5 SP1 (VSLive San Francisco 2009)
Dave Bost
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Sunpawet Somsin
 
MVC
MVCMVC
MVC
akshin
 
GHC
GHCGHC
GHC
AidIQ
 
Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handson
Prashant Kumar
 
Introduction To Mvc
Introduction To MvcIntroduction To Mvc
Introduction To Mvc
Volkan Uzun
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Maarten Balliauw
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
ivpol
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
yuvalb
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
micham
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
nspyre_net
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company india
Jignesh Aakoliya
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
ASP.NET 3.5 SP1 (VSLive San Francisco 2009)
ASP.NET 3.5 SP1 (VSLive San Francisco 2009)ASP.NET 3.5 SP1 (VSLive San Francisco 2009)
ASP.NET 3.5 SP1 (VSLive San Francisco 2009)
Dave Bost
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Sunpawet Somsin
 
Asp.net With mvc handson
Asp.net With mvc handsonAsp.net With mvc handson
Asp.net With mvc handson
Prashant Kumar
 
Ad

Recently uploaded (20)

Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Automation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From AnywhereAutomation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From Anywhere
Lynda Kane
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from AnywhereAutomation Hour 1/28/2022: Capture User Feedback from Anywhere
Automation Hour 1/28/2022: Capture User Feedback from Anywhere
Lynda Kane
 
Image processinglab image processing image processing
Image processinglab image processing  image processingImage processinglab image processing  image processing
Image processinglab image processing image processing
RaghadHany
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Automation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From AnywhereAutomation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From Anywhere
Lynda Kane
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical DebtBuckeye Dreamin 2024: Assessing and Resolving Technical Debt
Buckeye Dreamin 2024: Assessing and Resolving Technical Debt
Lynda Kane
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 

ASP.NET MVC introduction

  • 1. ASP.NET MVC 3 Introduction Twitter: @tomijuhola [email_address] +358 44 033 8639 Tomi Juhola, 14.6.2011 Versio: | Status: | Päivitetty: 0.1 Luonnos Tomi Juhola, 14.06.2011
  • 2. Motivation? Target? Needed to do slides about ASP.NET MVC Made promises Hard to find professional ASP.NET MVC developers TARGET: Get you everyone into basic ideas of ASP.NET MVC Make it easy to start developing simple web applications
  • 3. Agenda ASP.NET WEBFORMS VS. ASP.NET MVC ROUTING – FROM REQUEST TO FUNCTION CALLS CONTROLLER S & ACTION S VIEW – DISPLAYING DATA PASSING DATA
  • 4. ASP.NET WebForms VS. ASP.NET MVC 01
  • 5. ASP.NET WebForms Drag ’n drop GUI programming on web? Abstraction layer Issues: ViewState: Slow, hard to control Page life cycle No actual separation of concerns Very tight architecture (hard to e.g. unit test) No control over HTML
  • 6. ASP.NET MVC X New model (ALT.NET): Dec 2007 ASP.NET MVC CTP March 2009 ASP.NET MVC 1 Rapid development: March 2010 ASP.NET MVC 2 Jan 2011 ASP.NET MVC 3 Dec 2011 ASP.NET MVC 4? RTM already out!
  • 7. ASP.NET MVC benefits Familiar MVC architecture Close to HTTP: Request, update data, provide response Extensible by design Control over HTML & HTTP Testable by design Routing Mature technology beneath (ASP.NET) Modern API (.NET4, LINQ, lambda expr., extension methods etc.) Open source (MS-PL licensed) Convention over configuration
  • 8. Model – View - Controller Models implement the logic of the application Views display data and present the UI Controllers handle user interactions, work with the models and select next view to display -> Loose coupling, clear separation of concerns
  • 9. Project structure App_Data, e.g. resource files Content CSS, images, etc. Controllers, hmm.. The names of all controllers have to end with &quot;Controller&quot; Models, model classes Scripts, script files. By default, contains a bunch of js files. Views, View files like ViewPage (.aspx), ViewUserControl (.ascx), and ViewMasterPage (.master) files.
  • 10. Routing – from requests to function calls 02
  • 11. Routing ASP.NET MVC uses standard ASP.NET routing to direct HTTP requests to correct handlers (correct controller's action) Enables use of URLs that don't map to specific files Easier to read URLs Routing also handles automatically url parameter parsing to objects etc. Example route and routing rule: http://server/application/Products/show/beer, the routing parser passes the values Products, show, and beer to the page handler. URL pattern can be e.g. server/application/{area}/{action}/{category}
  • 12. Registering routes public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute(&quot;{resource}.axd/{*pathInfo}&quot;); // MapRoute parameters: Route name, URL with parameters // and parameter defaults routes. MapRoute (&quot;Default&quot;, &quot;{controller}/{action}/{id}&quot;, new { controller = &quot;Home&quot;, action = &quot;Index&quot;, id = &quot;&quot; } ); } protected void Application_Start() { RegisterRoutes (RouteTable.Routes); } }
  • 13. MVC request handling Order no Stage Details 0 Receive first request for the application In the Global.asax file, Route objects are added to the RouteTable object. 1. Perform routing The UrlRoutingModule module uses the first matching Route object in the RouteTable collection to create the RouteData object, which it then uses to create a RequestContext object. 2. Create MVC request handler The MvcRouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler. 3. Create controller The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object (typically an instance of the DefaultControllerFactory class) to create the controller instance with. 4. Execute controller The MvcHandler instance calls the controller's Execute method. 5. Invoke action For controllers that inherit from the ControllerBase class, the ControllerActionInvoker object that is associated with the controller determines which action method of the controller class to call, and then calls that method. 6. Execute result The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The built-in result types that can be executed include the following: ViewResult (which renders a view and is the most-often used result type), RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.
  • 14. Route default values public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute(&quot;Default&quot;, &quot;Category/{action}/{categoryName}&quot;, New { categoryName= &quot;food&quot;, action=&quot;show&quot;}); } URL Parameter values /Category action = &quot;show&quot; (default value) categoryName = &quot;food&quot; (default value) /Category/add action = &quot;add&quot; categoryName = &quot;food&quot; (default value) /Category/add/beer action = &quot;add&quot; categoryName= &quot;beverages&quot;
  • 16. Controllers and Actions Naming convention: xxxController Requested URLs are mapped to Controller classes and Action methods Base class for all controllers is Controller (and its base is ControllerBase) public class MyController : Controller { public ActionResult HelloWorld() { ViewBag.Message = &quot;Hello World!&quot;; return View(); } }
  • 17. ActionResult Base class for return values from actions Types (with helper method): ViewResult – Renders a Web page View() PartialViewResult – Renders a partial view PartialView() RedirectResult – Redirects to another URL Redirect() RedirectToRouteResult – Redirects to action RedirectToAction()/-Route() ContentResult – Returns a user def content Content() JsonResult – returns serialized JSON object Json() JavaScriptResult – returns JS script JavaScript() FileResult – Returns binary output File() EmptyResult - Same as null
  • 18. Non-action methods in Controller [NonAction] p ublic void DoSomething() { // L ogic. }
  • 20. Views Responsible for displaying data HTML & simple code If you’re doing complicated things in Views, you’re probably doing it wrong Convention: View returned by HomeController’s Index Action is \Views\Home\Index.aspx Example View: <%@ Page Language=&quot;C#&quot; MasterPageFile=&quot;/Views/Shared/Site.Master&quot; Inherits=&quot;System.Web.Mvc.ViewPage&quot; %> <asp:Content ID=&quot;aboutContent&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;> <h2>About</h2> <p> P ut content here. </p> </asp:Content>
  • 21. Site master (or _Layout.cshtml in Razor) Can be located from /Views/Shared/Site.Master (_Layout.cshtml) Used to create common page structure Important parts: In Site.Master:   <asp:ContentPlaceHolder ID=&quot;MainContent&quot; runat=&quot;server&quot; /> In actual pages: <%@ Page Title= ””  Language=&quot;C# ” MasterPageFile= ” ~/Views/Shared/Site.Master ”  Inherits= ” System.Web.Mvc.ViewPage< ModelType > ”  %> Include here: Common scripts CSSs Navigation etc. always visible bars
  • 22. HTML Helpers Used to create simple HTML elements (styling in CSS) Easy to tie into Models In views usable with following syntax: <% Html.ActionLink(…) %> Can be extended by extension methods, or own classes can be created Difference between <%: %>, <% %> and <%= %>? Renders with encoding, no rendering, renders withouth encoding Methods in HtmlHelper class ( http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.aspx ) ActionLink, BeginForm, CheckBox, Display, DropDownList, Editor, Hidden, Label, ListBox, Partial, Password, RadioButton, RenderAction, RenderPartial, RouteLink, TextArea, TextBox, ValidationSummary, ValidationMessage etc.
  • 23. Partial views Used to follow DRY principle (Don’t Repeat Yourself) Used to define a view that can be rendered inside parent view For this ASP.NET user controls are used (.ascx) Essential points: Shares same ViewData & ViewBag as parent Can be also strongly typed Consider these for e.g. basic forms, views etc. for each type you have This way the views & forms are similar in each page
  • 24. View engines ASP.NET MVC 3 adds also a new view engine: Razor There are others also available: Bellevue, Brail, Hasic, NDjango, NHaml, NVelocity, SharpTiles, Spark, StringTemplate, WingBeats, Xslt See: http://stackoverflow.com/questions/1451319/asp-net-mvc-view-engine-comparison and http://channel9.msdn.com/coding4fun/articles/Developer-Review-Four-ASPNET-MVC-View-Engines Instead of using <% … %> notation uses plain @ character. E.g. <h3>Hello, <%: name %>! </h3> vs. <h3>Hello, @name! </h3> <p>Now: <%: Datetime.Now %>! </p> vs. <p>Now: @DateTime.Now</p>
  • 25. Razor vs. traditional WebEngine Traditional <% if (Model.Value==true)%> <%{>% <% var outsideTemp = 79; var weatherMsg = &quot;Hello, it is &quot; + outsideTemp + &quot; degrees.&quot;; %> <p>Today's weather: <%: weatherMsg %> </p> <%}%> Razor @if (Model.Value==true) { @{ var outsideTemp = 79; var weatherMsg = &quot;Hello, it is &quot; + outsideTemp + &quot; degrees.&quot;; } <p>Today's weather: @ weatherMsg </p> }
  • 27. Method parameters By default, the parameters are retrieved from the request's data collection Contains name/values pairs for form data, query string values, and cookie values. There are several ways to access URL parameter values in the action methods Request and Response properties Automatically mapped parameters Examples with /Products/Detail?id=3 (or better /Products/Detail/3 , remember default routing?) public void Detail() { int id = Convert.ToInt32(Request[&quot;id&quot;]); } public ResultAction Detail(int id) { // Logic (id is already usable here) }
  • 28. Passing data to view Multiple choices: ViewData: ViewData[”name”]=”Matti”; ViewBag: ViewBag.Name = ”Matti”; Model: var person = new Person(”Matti”); return View(person); --- <%: Model.Name %> View should preferably be strongly typed with view specific model, use that to pass data Simple messages (like ”data updated”) can be handled with ViewBag ViewData is more legacy way of doing this If ViewData is used, use constants, instead of Magic Strings
  • 29. Strongly typed views & Scaffolding When creating a view you can define the model class for the view Can be also dynamic when the view is not strongly typed Strongly typed views allow also scaffolding of basic views So autogenerated forms, lists, details views etc.
  • 30. Strongly typed HtmlHelpers Named like: Html.NnnnFor(..) Html.TextBoxFor(..) Html.EditorFor(..) Html(TextAreaFor(..) Usage: <%= Html.LabelFor(model => model.ProductionVersion) %> Uses so called lambda syntax to strongly type the parameters Two kinds of strongly type helpers: Element level: TextBoxFor(), RadioButtonFor() Model level + others: EditorFor(), ValidationMessageFor()
  • 31. Form handling? Starting a form: <% using(Html.BeginForm(&quot;HandleForm&quot;, &quot;Home&quot;)) %> <% { %> <!-- Form content goes here --> <% } %> <% Html.BeginForm(); %> <!-- Form content goes here --> <% Html.EndForm(); %> Mapping: Enter your name: <%= Html.TextBox( ” name ” ) %> public ActionResult HandleForm(string name ) {} Mapping from Form-data: User.Name = Request.Form[” name” ]; More about forms: http://msdn.microsoft.com/en-us/library/dd410596.aspx
  • 32. Easiest way to map? From NerdDinner: public  ActionResult Edit(int  id, FormCollection formValues ) { Dinner dinner = dinnerRepository.GetDinner(id); UpdateModel(dinner, formValues); // Automatically updates dinnerRepository.Save(); return RedirectToAction(&quot;Details&quot;, new {id=dinner.DinnerID }); }
  • 33. What next? Validation ASP.NET MVC and jQuery Data access in ASP.NET MVC apps Custom HtmlHelpers Unit testing ASP.NET MVC Custom routing Security: XSS, Cross-site request forgery, cookie stealing, error reporting etc. Migration to MVC MVC & Web Forms together? Extending MVC, plugging in own handlers Etc.etc.etc.etc.
  • 34. Further reading (books for MVC 3 coming soon…) Professional ASP.NET MVC 2 by Jon Galloway, Scott Hanselman, Phil Haack, Scott Guthrie, Rob Conery (Wrox) Pro ASP.NET MVC 2 Framework by Steven Sanderson (Apress) Test-Drive ASP.NET MVC by Jonathan McCracken (Pragmatic bookshelf) ASP.NET MVC 2 in Action by Jeffrey Palermo, Ben Scheirman, Jimmy Bogard etc. (Manning)
  • 35. Web resources Official MVC site http://www.asp.net/mvc Blogs: http://weblogs.asp.net/scottgu/default.aspx http://haacked.com/ http://www.hanselman.com/blog/ http://blog.maartenballiauw.be/
  • 36. Example web apps http://nerddinner.codeplex.com/ http://flickrxplorer.codeplex.com/ http://kigg.codeplex.com/ http://codecampserver.codeplex.com/ http://orchardproject.net/ http://cartrackr.codeplex.com/ In MVC 1, anyone care to rewrite it in ASP.NET MVC 3?
  • 37. www.lindorff.fi Thanks! Tomi Juhola Development Lead Puh: 010 2700 00, Faksi: 010 2700 100 GSM: 044 033 8639 [email_address] www.lindorff.fi Joukahaisenkatu 2 FI-20100 Turku