Mvc summary


Published on

summary presentation for mvc can be used to quickly get in to mvc development

Published in: Education, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Mvc summary

  1. 1. What’s the Big Idea? Traditional ASP.NET Web Forms The idea was to make web development feel just the same as WindowsForms development.
  2. 2.  Traditional ASP.NET Web Forms development was a great idea, but reality proved more complicated. Over time, the use of Web Forms in real-world projects highlighted some shortcomings:1- View State weight(can reach hundreds of kilobytes in even modest web applications)2- Page life cycle (View State errors or finding that some event handlers mysteriously failto execute.)3- False sense of separation of concerns(ASP.NET’s code-behind model provides ameans to take application code out of its HTML markup and into a separate codebehindclass)4- Limited control over HTML5- Leaky abstraction (Web Forms tries to hide away HTML and HTTP wherever possible.)6- Low testability
  3. 3. 1. User interaction with an MVC application follows a natural cycle: the user takes an action, and in response the application changes its data model and delivers an updated view to the user.2. Tight Control over HTML and HTTP3. Testability4. Powerful Routing System5. Built on the Best Parts of the ASP.NET Platform6. Modern API7. ASP.NET MVC Is Open Source
  4. 4. Comparisons with ASP.NET Web Forms › your choice between the two is a matter of development philosophy. Consider these points: Web Forms. This makes it suitable for drag-anddrop Windows Forms–style development, in which you pull UI widgets onto a canvas and fill in code for their event handlers. MVC provides a simple, powerful, modern approach to writing web applications, with tidy code that’s easier to extend and maintain over time, and that’s free of bizarre complications and painful limitations.
  5. 5. The Web Platform Installer • Visual Studio 2010 SP1 • SQL Server Express 2008 R2 • ASP.NET MVC 3 Tools Update
  6. 6. Creating a New ASP.NET MVC Project  The Visual Studio MVC 3 project template
  7. 7. Creating a New ASP.NET MVC Project  Selecting a type of MVC 3 project
  8. 8. To add a controllerto our project, right-click the Controllersfolder in the VisualStudio SolutionExplorer window andchoose Add andthen Controller
  9. 9. The output form of our controller action methodModifying the HomeController Class
  10. 10. Setting the Scene We are going to imagine that a friend has decided to host a New Year’s Eve party and that she has asked us to create a web site that allows her invitees to electronically RSVP. She has asked for four key features: • A home page that shows information about the party • A form that can be used to RSVP • Validation for the RSVP form, which will display a thank-you page • RSVPs e-mailed to the party host when complete
  11. 11. A strongly typed view is intended to render a specificdomain type
  12. 12. Visual Studio IntelliSense for lambda expressions in HTML helper methodsASP.NET Web Forms supports only one server-side form in a web page, usually expressedas <form runat=“server”>, which is a container for the View State data and postbacklogic. MVC doesn’t use server-side forms. All forms are expressed using regular HTML, andyou can have as many of them as you like in a single view. There are no View State orother hidden form elements, and the ID values you assign to IDs don’t get mangled.
  13. 13. <link rel="Stylesheet" href="@Href("~/Content/Site.css")" type="text/css"/>
  14. 14.  Persistence is not part of our domain model. It is an independent or orthogonal concern in our separation of concerns pattern. This means that we don’t want to mix the code that handles persistence with the code that defines the domain model. The usual way to enforce separation between the domain model and the persistence system is to define repositories.
  15. 15.  Essential C# Features › Using Automatically Implemented Propertiespublic class Product { private string name; public string Name { get { return name; } set { name = value; } }}
  16. 16.  Essential C# Features › Using Extension Methods Extension methods are a convenient way of adding methods to classes that you don’t own and so can’t modify directly.
  17. 17.  Essential C# Features › Using Lambda Expressions Using a Delegate in an Extension MethodUsing a Lambda Expression to Replace a Delegate Definition
  18. 18.  Essential C# Features › Using Anonymous Types Creating an Anonymous Type Creating an Array of Anonymously Typed Objects
  19. 19.  Essential C# Features › Performing Language Integrated QueriesUsing LINQ to Query DataUsing LINQ Dot Notation
  20. 20. Including Multiple Functions in a Code Block
  21. 21. Passing Data Using the View Bag Feature
  22. 22. The dialog tells us to leave the layout reference blank if it is already set in a _viewstart file. If you look in the Views folder in your MVC project, you will see a file called _ViewStart.cshtmlSpecifying a Razor layout when creating aview The _ViewStart.cshtml FileNote : View files that start with an underscore (_) are not returned to the user, even ifthey are requested directly.
  23. 23. The _Layout.cshtml FileA layout is the equivalent of the ASPX master page.
  24. 24. Using Ninject  The relationships among four simple typesOur objective is to be able to create instances of ShoppingCart and injectan implementation of the IValueCalculator class as a constructorparameter. This is the role that Ninject, our preferred DI container, plays forus. But before we can demonstrate Ninject, we need to get set up in VisualStudio.
  25. 25.  Creating the Project › Adding Ninject
  26. 26.  Getting Started with Ninject Preparing a Ninject Kernel 1 Binding a Type to Ninject 2
  27. 27.  Getting Started › Creating the Visual Studio Solution and Projects
  28. 28.  Getting Started › Creating the Visual Studio Solution and Projects  The Three SportsStore Projects
  29. 29. Getting Started  Creating the Visual Studio Solution and Projects ›The projects shown in theSolution Explorer window
  30. 30.  Starting the Domain Model Creating the Product class
  31. 31.  Creating an Abstract Repository › Create a new top-level folder inside the SportsStore.Domain project called Abstract and a new interface called IProductsRepository The IProductRepository Interface File
  32. 32.  Displaying a List of Products › Adding a Controller
  33. 33.  Displaying a List of Products › Adding the View The List.cshtml View
  34. 34.  Displaying a List of Products › Setting the Default Route Adding the Default Route Global.asax.cs
  35. 35.  Displaying a List of Products › Running the Application Viewing the basic application functionality
  36. 36.  Preparing a Database › We are going to use SQL Server as the database, and we will access the database using the EntityFramework (EF), which is the .NET ORM framework.  Adding Data to the Database
  37. 37.  Creating the Product Repository EFProductRepository.cs Adding the Real Repository Binding
  38. 38. The result of implementing the real repository 
  39. 39.  Adding Pagination › Displaying Page Links List.cshtml the new view model The page links
  40. 40. Adding Pagination Displaying Page Links ›
  41. 41. Improving the URLs The new URL scheme displayed in the browser
  42. 42. Styling the Content The design goal for the SportsStore application
  43. 43.  Styling the Content  Run
  44. 44. Creating a Partial View Using a Partial View from List.cshtml
  45. 45. Applying a partial view 
  46. 46.  Adding Navigation Controls › Filtering the Product List  Adding Category Support to the List Action Method
  47. 47.  Adding Navigation Controls › Filtering the Product List  http://localhost:23081/?category=Soccer Using the query string to filter by category
  48. 48. Adding NavigationControls Refining the URL Scheme Empty and Paging Category and Paging
  49. 49. Building a Category Navigation Menu Implementing the Menu Metho Generating Category Lists
  50. 50. Building a Category Navigation Menu 
  51. 51.  Building the Shopping Cart The basic shopping cart flow
  52. 52. Defining the Cart Entity
  53. 53. Building the Shopping Cart Implementing the Cart ControllerWe need to create a controller to handle the Add to cart button presses. Create a newcontroller called CartController
  54. 54. The Index View
  55. 55.  Completing the Cart › Removing Items from the Cart  we are going to do by adding a Remove button in each row of the cart summary. The changes to Views/Cart/Index.cshtml
  56. 56. Completing the Cart  Removing Items from the Cart ›Removing an item from the shopping cart
  57. 57.  Submitting Orders › Adding the Checkout Process
  58. 58. The shipping details form
  59. 59.  Submitting Orders › Displaying Validation Errors  Adding a Validation Summary
  60. 60.  Submitting Orders › Displaying a Summary Page  Right-click either of the Checkout methods in the CartController class and select Add View from the pop-up menu. Set the name of the view to Completed The Completed.cshtml View The thank-you page
  61. 61.  Adding Catalog Management › The convention for managing collections of items is to present the user with two types of pages: a list page and an edit page Sketch of a CRUD UI for the product catalog
  62. 62.  Creating a CRUD Controller › We want to demonstrate how to build up the controller and explain each step as we go. So, remove all of the methods in the controllerRendering a Grid of Products in the Repository The Index Action Method
  63. 63.  Creating a CRUD View › Creating a New Layout  Right-click the Views/Shared folder in the SportsStore.WebUI project and select Add > New Item. Select the MVC 3 Layout Page (Razor) template and set the name to _AdminLayout.cshtml Creating a new Razor layout
  64. 64.  Creating a CRUD View › Implementing the List View When using the List scaffold, Visual Studio assumes you are working with an IEnumerable sequence of the model view type, so you can just select the singular form of the class from the list.
  65. 65.  Creating a CRUD Controller › Modifying the Index.cshtml
  66. 66.  Creating a CRUD Controller › Creating the Edit View
  67. 67.  Creating a CRUD Controller › Creating the Edit View Using Model Metadata
  68. 68.  Creating a CRUD Controller › Handling Edit POST Requests
  69. 69.  Creating a CRUD Controller › Displaying a Confirmation Message
  70. 70.  Creating a CRUD Controller › Adding Model Validation Applying Validation Attributes to the Product Class
  71. 71.  Creating a CRUD Controller › Enabling Client-Side Validation
  72. 72.  Creating a CRUD Controller › Creating New Products  First, add the Create method to the AdminController class.This leads us to the modification. We would usually expect a form to postback to the action thatrendered it, and this is what the Html.BeginForm assumes by default when it generates an HTMLform.Now the form will always be posted to the Edit action, regardless of which action rendered it.
  73. 73.  Creating a CRUD Controller › Creating New Products
  74. 74.  Creating a CRUD Controller › Deleting Products Adding a Method to Delete Products Implementing Deletion Support in the Entity Framework Repository Class The Delete Action Method
  75. 75.  Securing the Administration Features › Setting Up Forms Authentication  Applying Authorization with Filters Adding the Authorize Attribute to the Controller Class You can apply filters to an individual action method or to a controller. When you apply a filter to a controller, it works as though you had applied it to every action method in the controller class. We applied the Authorize filter to the class, so all of the action methods in the Admin controller are available only to authenticated users.
  76. 76.  Securing the Administration Features › Setting Up Forms Authentication  Creating the View Right-click in one of the action methods in the Account controller class and select Add View from the popup menu. Create a strongly typed view called LogOn that uses LogOnViewModel as the view model type The LogOn View
  77. 77.  Image Uploads › Updating the Entity Framework Conceptual Model
  78. 78. Image Uploads 
  79. 79.  Image Uploads
  80. 80. Overview of MVC ProjectsThe initialconfiguration ofMVC projectscreated using theEmpty, InternetApplication, andIntranet Applicationtemplates
  81. 81. Summary of MVC 3 Project Items
  82. 82. URLs, Routing, and Areas Matching URLsTable highlights two key behaviors of URL patterns:• URL patterns are conservative, and will match only URLs that have the same number of segments as the pattern. You can see this in the fourth and fifth examples in the table.• URL patterns are liberal. If a URL does have the correct number of segments, the pattern will extract the value for the segment variable, whatever it might be.
  83. 83. URLs, Routing, and AreasCreating and Registering a Simple Route Registering a RouteA more convenient way of registering routes is to use the MapRoutemethod defined in the RouteCollection class.
  84. 84. URLs, Routing, and AreasMixing Static URL Segments and Default ValuesAliasing a Controller and an Action
  85. 85. URLs, Routing, and AreasUsing Custom Variables as Action Method Parameters If we define parameters to our action method with names that match the URL pattern variables, the MVC Framework will pass the values obtained from the URL as parameters to the action method.Defining Optional URL Segments This route will match URLs whether or not the id segment has been supplied.
  86. 86. URLs, Routing, and Areas Routing Requests for Disk Files We still need a way to serve content such as images, static HTML files, JavaScript libraries, and so on. As a demonstration, we have created a file called StaticContent.html in the Content folder of our example MVC application.By default, the routing system checks to see ifa URL matches a disk file before evaluatingthe application’s routes. If there is a match,then the disk file is served, and the routes arenever used. We can reverse this behavior sothat our routes are evaluated before disk filesare checked by setting the RouteExistingFilesproperty of the RouteCollection to true,
  87. 87. URLs, Routing, and AreasGenerating Outgoing URLs in Views The simplest way to generate an outgoing URL in a view is to call the Html.ActionLink method within a view @Html.ActionLink("About this application", "About") <a href="/Home/About">About this application</a>Targeting Other Controllers The default version of the ActionLink method assumes that you want to target an action method in the same controller that has caused the view to be rendered. To create an outgoing URL that targets a different controller, you can use a different overload that allows you to specify the controller name @Html.ActionLink("About this application", "About", "MyController") <a href="/MyController/About">About this application</a> Passing Extra Values @Html.ActionLink("About this application", "About", new { id = "MyID" }) <a href="/Home/About/MyID">About this application</a>
  88. 88. URLs, Routing, and AreasGenerating URLs (and Not Links) My URL is: @Url.Action("Index", "Home", new { id = "MyId" }) My URL is: /Home/Index/MyIdGenerating Links and URLs from Routing Data Sometimes it is useful to treat controller and action just like any other variables, and to generate a link or URL by providing a collection of name/value pairs. We can do this by using helper methods that are not MVC- specific Generating a Link Using an Anonymous Type @Html.RouteLink("Routed Link", new { controller = "Home", action = "About", id="MyID"}) <a href="/Home/About/MyID">Routed Link</a> Generating a URL Using an Anonymous Type @Url.RouteUrl(new { controller = "Home", action = "About", id = "MyID" })
  89. 89. URLs, Routing, and AreasWorking with Areas The MVC Framework supports organizing a web application into areas, where each area represents a functional segment of the application, such as administration, billing, customer support, and so on. This is useful in a large project, where having a single set of folders for all of the controllers, views, and models can become difficult to manage. Creating an Area To add an area to an MVC application, right-click the project item in the Solution Explorer window and select Add > Area.
  90. 90. URLs, Routing, and AreasPopulating an Area To complete this simple example, we can create a view by right-clicking inside the Index action method and selecting Add > View from the pop-up menu
  91. 91. Controllers and ActionsCreating a Controller by Deriving from the Controller Class
  92. 92.  Getting Data from Context Objects
  93. 93. Controllers and Actions Using Action Method Parameters The names of our parameters are treated case-insensitively, so that an action method parameter called city can be populated by a value from Request.Form["City"].
  94. 94. Controllers and ActionsSpecifying Default Parameter Values If you want to process requests that don’t contain values for action method parameters, but you would rather not check for null values in your code or have exceptions thrown, you can use the C# optional parameter feature instead. If a request does contain a value for a parameter but it cannot be converted to the correct type (for example, if the user gives a nonnumeric string for an int parameter), then the framework will pass the default value for that parameter type (for example, 0 for an int parameter), and will register the attempted value as a validation error in a special context object called ModelState. Unless you check for validation errors in ModelState, you can get into odd situations where the user has entered bad data into a form, but the request is processed as though the user had not entered any data or had entered the default value.
  95. 95. Controllers and ActionsBuilt-inActionResultTypes
  96. 96. Controllers and ActionsBuilt-in ActionResult Types
  97. 97. Controllers and ActionsReturning HTML by Rendering a View
  98. 98. Controllers and ActionsReturning HTML by Rendering a View When the MVC Framework calls the ExecuteResult method of the ViewResult object, a search will begin for the view that you have specified, the framework will look in the following locations: using areas in your project not using areas, or you are using areas but none of the files in the preceding list have been found
  99. 99. Controllers and ActionsPassing Data from an Action Method to a View Providing a View Model Object
  100. 100. Controllers and ActionsReturning HTML by Rendering a View Passing Data with the ViewBagThe ViewBag has an advantage over using a view model object in that it iseasy to send multiple objects to the view. If we were restricted to using viewmodels, then we would need to create a new type that had string andDateTime members in order to get the same effects, When working withdynamic objects, you can enter any sequence of method and propertycalls in the view, like this:The day is: @ViewBag.Date.DayOfWeek.Blah.Blah.Blah
  101. 101. Controllers and ActionsRedirecting to a Literal URL Redirecting to a Literal URL Permanently Redirecting to a Literal URLRedirecting to a Routing System URL Redirecting to a Routing System URL
  102. 102. Controllers and ActionsReturning Text Data You can omit the last two parameters, in which case the framework assumes that the data is HTML (which has the content type of text/html). It will try to select an encoding format that the browser has declared support for when it made the request you are processing. This allows you to return just text, like this: return Content("This is plain text"); In fact, you can go a little further. If you return any object from an action method that isn’t an ActionResult, the MVC Framework will try to serialize the data to a string value and send it to the
  103. 103. Controllers and ActionsReturning XML Data Returning XML data from an action method is very simple, especially when you are using LINQ to XML and the XDocument API to generate XML from objects.
  104. 104. Controllers and ActionsReturning JSON Data
  105. 105. Controllers and ActionsReturning Files and Binary Data Sending a File
  106. 106. Controllers and ActionsSending a Byte ArraySending the Contents of a Stream
  107. 107. Controllers and ActionsReturning Errors and HTTP Codes Sending a Specific HTTP Result Code The constructor parameters for HttpStatusCodeResult are the numeric status code and an optional descriptive message. In the listing, we have returned code 404, which signifies that the requested resource doesn’t exist.
  108. 108. Controllers and ActionsSending a 404 ResultSending a 401 Result Another wrapper class for a specific HTTP status code is HttpUnauthorizedResult, which returns the 401 code, used to indicate that a request is unauthorized.
  109. 109. Controllers and ActionsThe output from a custom action result
  110. 110. FiltersIntroducing the Four Basic Types of Filters
  111. 111. FiltersApplying Filters to Controllers and Action Methods You can apply multiple filters, and mix and match the levels at which they are applied— that is, whether they are applied to the controller or an individual action method.
  112. 112. FiltersUsing the Built-in Filters
  113. 113. FiltersUsing the RequireHttps Filter The RequireHttps filter allows you to enforce the use of the HTTPS protocol for actions. It redirects the user’s browser to the same action, but using the https:// protocol prefix. You can override the HandleNonHttpsRequest method to create custom behavior when an unsecured request is made. This filter applies to only GET requests. Form data values would be lost if a POST request were redirected in this way.
  114. 114. FiltersUsing the OutputCache Filter The OutputCache filter tells the MVC Framework to cache the output from an action method so that the same content can be reused to service subsequent requests for the same URL. Caching action output can offer a significant increase in performance, because most of the time-consuming activities required to process a request (such as querying a database) are avoided. Of course, the downside of caching is that you are limited to producing the exact same response to all requests, which isn’t suitable for all action methods. The OutputCache filter uses the output caching facility from the core ASP.NET platform, and you will recognize the configuration options if you have ever used output caching in a Web Forms application. The OutputCache filter can be used to control client-side caching by affecting the values sent in the Cache-Control header.
  115. 115. FiltersCaching the Output of a Child ActionThe controller in the listing defines two action methods:• The ChildAction method has the OutputCache filter applied. This is the action method we will call from within the view.• The Index action method will be the parent action.Both action methods write the time that they were executed to the Responseobject.
  116. 116. FiltersCaching the Output of a Child Action The ChildAction.cshtml View A View That Calls a Cached Child Action
  117. 117. ViewsAdding Dynamic Content to a Razor View
  118. 118. ViewsUsing HTML Helpers Creating an Inline HTML Helper The most direct way to create a helper is to do so in the view, using the Razor @helper tag
  119. 119. ViewsUsing Input Helpers Basic Input HTML Helpers
  120. 120. ViewsUsing Strongly Typed Input Helpers
  121. 121. ViewsCreating Select Elements
  122. 122. Views Creating a Sequence of Objects to Be Displayed by the WebGrid HelperUsing the WebGrid Helper
  123. 123. ViewsUsing the WebGrid Helper
  124. 124. ViewsUsing the Chart Helper
  125. 125. ViewsUsing Other Built-In Helpers
  126. 126. Views Using Sections
  127. 127. Views Using Sections
  128. 128. ViewsUsing Sections
  129. 129. ViewsUsing Partial Views
  130. 130. Views A Strongly Typed Partial ViewUsing Strongly Typed Partial Views
  131. 131. ViewsUsing Child Actions Creating a Child Action Any action can be used as a child action. Rendering a Child Action A Child Action Calling a Child Action A Partial View for Use with a Child Action
  132. 132. Model TemplatesA View That Uses Templated HTML Helpers
  133. 133. Model TemplatesCreating Read-Only HTML Using Templated Helpers
  134. 134. Model TemplatesThe MVC Scaffolding Templated HTML Helpers
  135. 135. Model TemplatesUsing Model Metadata Using Metadata to Control Editing and Visibility Using the HiddenInput Attribute Hiding model object properties from the user
  136. 136. Model TemplatesUsing Metadata for Data Values
  137. 137. Model TemplatesWorking with Complex Type Parameters
  138. 138. Model TemplatesCustomizing the Templated View Helper System Creating a Custom Editor Template One of the easiest ways of customizing the templated helpers is to create a custom template. This allows us to render exactly the HTML we want. As an example, we are going to create a custom template for the Role property in our Person class. This property is typed to be a value from the Role enumeration, but the way that this is rendered by default is problematic.
  139. 139. Model TemplatesCustomizing the Templated View Helper System Creating a Custom Editor Template
  140. 140. Model BindingUsing the Default Model Binder The Order in Which the DefaultModelBinder Class Looks for Parameter Data The locations are searched in order. For example, in the case of the action method shown before, the DefaultModelBinder class examines our action method and finds that there is one parameter, called id.
  141. 141. Model BindingBinding to Arrays and Collections One elegant feature of the default model binder is how it deals with multiple data items that have the same name. A View That Renders HTML We have used the Html.TextBox helper to create Elements with the Same Name three input elements; these will all be created with a value of movies for the name attribute Receiving Multiple Data Items in an Action Method
  142. 142. Model BindingUsing Model Binding to Receive File Uploads All we have to do to receive uploaded files is to define an action method that takes a parameter of the HttpPostedFileBase type. The model binder will populate it with the data corresponding to an uploaded file.
  143. 143. Model Validation The progression of views in the sample applicationCurrently, our application will accept any data the user submits, but to preserve theintegrity of our application and domain model, we require three things to be true beforewe accept an Appointment that the user has submitted:• The user must provide a name.• The user must provide a date (in the mm/dd/yyyy format) that is in the future.• The user must have checked the checkbox to accept the terms and conditions.
  144. 144. Model ValidationExplicitly Validating a Model Errors result in highlighted elements
  145. 145. Model ValidationDisplaying Validation Messages
  146. 146. Model ValidationDisplaying Property-Level Validation Messages Using the per-property validation message helper Displaying model and property validation errors
  147. 147. Model ValidationSpecifying Validation Rules Using Metadata
  148. 148. Model Validation The Built-in Validation Attributes
  149. 149. Model ValidationPerforming Client-Side Validation
  150. 150. Model ValidationPerforming Remote ValidationActions methods that support remote validation must return the JsonResult type, andthe method parameter must match the name of the field being validated; in ourcase, this is Date. We make sure that we can parse a DateTime object from the valuethat the user has submitted and, if we can, check to see that the date is in the future
  151. 151. Unobtrusive Ajax Using MVC Unobtrusive AjaxEnabling and DisablingUnobtrusive Ajax The non-Ajax example web application
  152. 152. Unobtrusive AjaxUsing Unobtrusive Ajax Forms
  153. 153. Unobtrusive AjaxAjaxOptions Properties
  154. 154. Unobtrusive AjaxProviding the User with Feedback While Making an Ajax Request
  155. 155. Unobtrusive AjaxCreating Ajax Links
  156. 156. Unobtrusive AjaxWorkingwith AjaxCallbacks
  157. 157. Unobtrusive AjaxProcessing JSON in the Browser Notice that we have not set a value for the UpdateTargetId. We can’t rely on the unobtrusive Ajax script to process the JSON data we get from the server because it is no longer HTML. Instead, we need to write a JavaScript function that will process the JSON and generate the HTML we need in the browser.