Your SlideShare is downloading. ×
0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
ASP.NET MVC 2.0
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

ASP.NET MVC 2.0

6,765

Published on

Training slides for Microsoft customers

Training slides for Microsoft customers

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
6,765
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
117
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. ASP.NET MVC 2.0 10/29/2010
  • 2. Buu Nguyen • Microsoft MVP, MCSD.NET, SCJD, SCBCD • Vice President of Technology, KMS Technology • Lecturer, RMIT University Vietnam
  • 3. Table of Contents Core • ASP.NET MVC Basics • Routing • Controllers & Action Methods • View Results & Views Advanced • Action Method Selectors • Filters • Model Validation • Model Templates • And beyond…
  • 4. ASP.NET MVC BASICS
  • 5. Overview of ASP.NET MVC • MVC-based .NET web development platform • Alternative, not replacement, for Web Forms • Built openly & iteratively (http://www.codeplex.com/aspnet) • Releases • Latest RTM release is ASP.NET MVC 2.0 • Latest release is ASP.NET 3.0 Beta
  • 6. Technology Stack ASP.NET Web Forms ASP.NET MVC ASP.NET Framework (Configuration, Security, Membership, Roles, Profiles, Routing, Caching, Session, Application State, Cookie, .aspx/.ascx/.asax/.master files etc. .NET Framework
  • 7. ASP.NET MVC Pros & Cons Advantages • Clear separation of concerns • Testability & TDD • Tight-control over markup • Extensibility • Search-engine friendliness • Good parts of ASP.NET Disadvantages • No out-of-the-box rich UI helper methods • Learning curve is (a bit) stiffer than Web Forms • Community is not yet as crowded as Web Forms
  • 8. Project Structure • Project Conventions • Content: CSS, images etc. • Controllers: controller classes • Models: model classes • Views • [Controller]: controller-specific views • Shared: master pages, user controls, shared views etc. • Scripts: JavaScript files
  • 9. MvcHandler Action Result Controller Factory Action View Engine View View Result Controller forwards invokes produces produces defines Model Route maps
  • 10. About TodoApp • Allow users to manage tasks • To spend our time wisely, we‟ll: • Utilize the Membership API for user management • Use Entity Framework for DB logic
  • 11. Let’s see the completed TodoApp
  • 12. ROUTING
  • 13. Overview • Enabled by UrlRoutingModule • Introduced since ASP.NET 3.5 SP1 • Independent from ASP.NET MVC • Responsibilities • Map incoming URLs to route info • Construct outgoing URLs from route info
  • 14. Incoming URL to Route Info actual value becomes TaskController.cs
  • 15. Route Constraints • Strings (regular expression) • Classes implementing IRouteConstraint  E.g. HttpMethodConstraint  Custom constraints
  • 16. Outgoing URLs & Links • Generate outgoing URL from route info • UrlHelper#Action(…) • Generate outgoing link from route info • HtmlHelper#ActionLink(…)
  • 17. MvcHandler Action Result Controller Factory Action View Engine View View Result Controller forwards invokes produces produces defines Model Route maps
  • 18. CONTROLLERS & ACTION METHODS
  • 19. Controllers • Usually inherit from Controller class • Can directly inherit from IController interface • Usually correspond to an entity or domain concept • Instantiated by a controller factory • Can create a custom controller factory (e.g. to apply dependency injection)
  • 20. Action Methods • Public methods of a controller • Each action method corresponds to 1 HTTP request & response • Input sources for action methods • Context objects • Parameters • Output of action methods is an object implementing ActionResult interface
  • 21. Input #1 – Common Context Objects • Request.QueryString • Request.Form • Request.Cookie • Request.Headers • HttpContext.Application • HttpContext.Session • HttpContext.Items • HttpContext.Cache • RouteData.Values • User • Authentication info of the current user • TempData • Data stored in the previous request in the same session • etc.
  • 22. Input #2 – Action Method Parameters • Action methods have their parameters supplied from the following sources • Request.QueryString • Request.Form • RouteData.Values • Complex-typed parameters can be supplied too • This is called model binding • It‟s possible to implement custom model binders
  • 23. Action Method Results • Action methods return objects implementing ActionResult • Each subclass overrides ExecuteResult() method to work with the Response object • Send file, redirect, render HTML etc. • It‟s possible to implement custom action result
  • 24. Built-in Action Result Types Action Result Type Examples of Use (in action methods) ViewResult return View(); return View(“view”, modelObject); PartialViewResult return PartialView(); return PartialView(“partialview”, modelObject); RedirectToRouteResult return RedirectToRoute(“LogOn”); RedirectResult return Redirect(“http://www.microsoft.com”); ContentResult return Content(rss, “application/rss+xml”); FileResult return File(“chart.ppt”, “application/ppt”); JsonResult return Json(someObject); JavaScriptResult return JavaScript("$(„#table‟).init();"); HttpUnauthorizedResult return new HttpUnauthorizedResult(); EmptyResult return new EmptyResult(); ActionResult Base class for all action results, including custom ones
  • 25. MvcHandler Action Result Controller Factory Action View Engine View View Result Controller forwards invokes produces produces defines Model Route maps
  • 26. VIEW RESULTS & VIEWS
  • 27. ViewResult • The call to View(…) generates a ViewResult object • ViewResult lookups a view engine to render the content • The default view engine is WebFormViewEngine • ASP.NET MVC 3 is shipped with the Razor view engine • Custom view engines for XSLT, Brail, NHaml, etc. are available • View path lookup • Either View("~/path/to/some/view.aspx"); • Or if controller (& action) are specified • /Views/ControllerName/ViewName.aspx • /Views/ControllerName/ViewName.ascx • /Views/Shared/ViewName.aspx • /Views/Shared/ViewName.ascx
  • 28. ViewData • Controllers pass data to view via the ViewData dictionary • Directly, e.g. ViewData[“key”] = obj; • View model object, e.g. ViewData.Model = obj
  • 29. ViewData Dictionary
  • 30. Model Object
  • 31. The Familiar Web Forms View • You can reuse most of your ASP.NET Web Form knowledge, for examples: • Directives & syntax • Localization • Master page • (MVC) user control • Things you shouldn‟t use: • Server control (unless reusing) • Code-behind & Web Forms life-cycle • Things you couldn‟t use: • View state • Post back
  • 32. Dynamic Code Options Technique Description Inline code The same old <% … %> and <%= … %> HTML Helpers Built-in or extension methods for HtmlHelper class, e.g. Html.TextBox(…), Html.BeginForm(…) etc. Partial views Render MVC user controls, which can be reused in many places, e.g. Html.RenderPartial(“Task”) Partial action Invoke an MVC action and execute returned action result, e.g. Html.RenderAction("ShowTagCloud", "BlogEntry") Server controls Using standard ASPX control registration & using syntax
  • 33. Common HtmlHelper Methods • For each of the above, there‟s a corresponding Html.XxxFor(…) method that works with expression tree Method Corresponding HTML Html.CheckBox(…) <input id=“…" name=“…" type="checkbox" value=“…" …/> Html.TextBox(…) <input id=“…" name=“…" type="text" value=“…" …/> Html.TextArea(…) <textarea id=“…" name=“…" …>…</textarea> Html.Password(…) <input id=“…" name=“…" type=“…" value=“…" …/> Html.RadioButton(…) <input checked=“…" id=“…" name=“…" type=“…" value=“…" …/> Html.Hidden(…) <input id=“…" name=“…" type=“…" value=“…" …/> Html.BeginForm(...) <form id=“…” …>…</form>
  • 34. Custom HtmlHelper Methods
  • 35. MvcHandler Action Result Controller Factory Action View Engine View View Result Controller forwards invokes produces produces defines Model Route maps
  • 36. ACTION METHOD SELECTORS
  • 37. Action Method Selectors • Attributes used in Controller#Execute() to know which action to invoke • Built-in selectors • AcceptVerbs(HttpVerbs) • Or more convenient versions: HttpGet & HttpPost • Inherit ActionMethodSelectorAttribute • Override bool IsValidForRequest(…)
  • 38. FILTERS
  • 39. Filters • .NET attributes adding logic • Before & after action method invocation • Before & after action result invocation • During unhandled exception • During request authorization • Filters can be applied to • Individual action • All actions in a controller • Built-in filters: OutputCacheAttribute, AuthorizeAttribute, ValidateInputAttribute, ValidateAntiForgeryTokenAttribute, HandleErrorAttribute, ChildActionOnly
  • 40. Types of Filter Filter Type Interface Methods to Override Authorization filter IAuthorizationFilter OnAuthorization() Action filter IActionFilter OnActionExecuting(), OnActionExecuted() Result filter IResultFilter OnResultExecuting(), OnResultExecuted() Exception filter IExceptionFilter OnException()
  • 41. MODEL VALIDATION
  • 42. Business Rule Validation • Business rules needs enforcing • User name must be supplied • Email format must be correct • It‟s also desirable to enforce rules at both server- side and client-side • DRY principle must be followed for maintainability
  • 43. ASP.NET MVC Model Validation • Apply one or more validation attributes to the model classes and/or their properties • The model binding process validates and populates ModelState.Errors collection • Check result with ModelState.IsValid or ModelState.IsValidField(propertyName) • More error can be added after model binding • ModelState.AddModelError(key, message); • key: use string.Empty for non-property error
  • 44. DataAnnotations Validation Attributes Attribute Description Range Validates whether the property value falls in a min-max range RegularExpression Validates the property against a specified regular expression Required Validates whether the property value is provided StringLength Validates the maximum length of a property value Validation The base class for all validation attributes, including custom attributes
  • 45. Model Validation in Views • Html Helper Methods • Html.ValidationSummary( bool excludePropertyErrors, string message) • Html. ValidationMessage( string modelName) • Html. ValidationMessageFor( Expression<Func<TModel, TProperty>> expression) • Html.EnableClientValidation() • References to JavaScript files • ~/scripts/jquery-1.3.2.min.js • ~/scripts/jquery.validate.min.js • ~/scripts/MicrosoftMvcJQueryValidation.js
  • 46. MODEL TEMPLATES
  • 47. Model Templates • Developers describe rendering rules using metadata • ASP.NET MVC renders based on metadata using built-in or custom templates
  • 48. DataAnnotations UI Attributes Attribute Description DisplayName Used in Html.Label()/LabelFor() to generate the label text HiddenInput Generates a hidden input for the property DataType Indicates the data type of the property (e.g. Email, Password) ScaffoldColumn Indicates whether the property should be shown or ignored DisplayFormat Adds formatting rules to the property (e.g. DataFormatString, NullDisplayText etc.) ReadOnly Indicates that users shouldn‟t be able to modify the property UIHint Specifies a template to use
  • 49. Model Templates in Views • Display • Html.Display(“PropertyName”) • Html.DisplayFor(model => model.PropertyName) • Html.DisplayForModel() • Editor • Html.Editor(“PropertyName”) • Html.EditorFor(model => model.PropertyName) • Html.EditorForModel()
  • 50. AND BEYOND…
  • 51. And Beyond… ASP.NET MVC 2 • Areas • Asynchronous controller ASP.NET MVC 3 Beta • Razor view engine • NuPack • Global filters • JSON model binding • Better DI support • …
  • 52. THANK YOU! buunguyen@kms-technology.com http://vn.linkedin.com/in/buunguyen www.twitter.com/buunguyen

×