Conheça oASP.NET MVC 2Daniel FerreiraMSP | MCP | MCTS | MCPDC.E.S.A.R@dfsdaniel
AgendaResumo
Slide do obrigado!Háalgum tempo atrás…ASP.NETCachingModulesGlobalizationPagesControlsMaster PagesProfileRolesMembershipIntrinsicsHandlersEtc.Um único framework paradesenvolvimento web
O ASP.NET Hoje!ASP.NETDynamic DataPresentationASP.NETWebFormsASP.NETMVCASP.NETCoreRuntime
WebFormsis great, but options are good…
Master PageControlControlUIPresentation LogicBusiness LogicData AccessControlControlPageControlControlControlControlQuemfaz o que?Como e quando?Semdivisão de responsabilidades
Abstração de controlespodenãoseruma boa idéia…
Controller(Input)Model(Logic)View(Presentation)Separação de interesses!O Padrão MVC
ControllerControllerHandles input(HTTP requests)RequestViewViewVisually representsthe modelResponsePor outro ângulo…
O ASP.NET MVC FrameworkNamespace: System.Web.MvcUm novo template de projeto no Visual StudioUma nova maneira de desenvolver com ASP.NETNão é uma nova versão dos webformsFoco na arquitetura do projeto
O ASP.NET MVC FrameworkRoadmap:Prédaversão 1 VS 2008 (dez/07 a mar/09)Versão 1.0 VS 2008 (mar/09)Versão 1.1 VS 2010 beta 1 (jun/09)Prédaversão 2 VS 2008 e VS 2010 (jul/09)Versão 2 VS 2008 e VS 2010 (primeirotrimestre de 2010)
ASP.NET MVC 2.0
Novidadesda versão 2.0Agrupamentoporáreas in-the-boxData Annotations ValidationTemplates Helpers HTMLHttpPostAttributeAdição do DefaultValueAttributeClient-side validationRequireHttpsAttributeModel Validation ProvidersMetadata Providers
Áreas – Preview 1Partição e agrupamento de funcionalidadesporáreas;Permitemaiormodularidade e separação.Suporte nativo a URLs mais simpáticas:“/Area1/Controlador1” ou“/Area2/Controlador1”14
Áreas – Preview 2Suporte “in-the-box” semnecessidade de múltiplosprojetos“AddArea” DialogRegistro de rota dinamicamente (AreaRegistration.cs)15
Áreas
HTML HelpersUso de expressões lambda fortemente tipadas por padrão;Visualização do erro em tempo de compilação;Melhor suporte ao intellisense dentro das views.Preview 1: Html.EditorFor(), Html.LabelFor() e Html.DisplayFor() Preview 2:Html.TextBoxFor(), Html.TextAreaFor(), Html.DropDownListFor(), Html.HiddenFor(), e Html.ValidationMessageFor()
HTML HelpersouAntesAgora
TemplatesPermite customizar a exibição dos itens do EditorFor()Não precisa colocar o IDUso do atributo UIHint no objectmodelReaproveitamento de código
Templates
DataAnnotationsHTMLHelpers
ValidaçãoSuporte nativo para validação através de DataAnnotationDeclaração de regras nos ObjectModelsNamespace System.ComponentModel.DataAnnotationsValidationAttribute como classe base para criação de atributos de validação personalizadosSuporte a outras validações como o CastleValidator, EntLibValidation, etc)
Classes de Validação
Validação com DataAnnotationspublic classCustomer{[Required]public stringName{get; set; }[Range(1, 120, ErrorMessage="Invalid age")]public intAge{ get; set; }[RegularExpression(@"^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$", ErrorMessage="Invalid email")]public string Email{get; set; }[UIHint("CountryDropDown")]public string Country {get; set;}[DisplayName("Is Active Customer:")]public bool IsActive{get; set; }}
Client-side validationTambém é possível fazer a validação do lado do cliente de forma mais direta;Intregação do xVal + DataAnnotations + JQueryJá incluso os plugins de validação do JQuery 1.3.2
HttpPostAttributeAntes:Agora:[AcceptVerbs(HttpVerbs.Post)] publicActionResult Create(Post post) [HttpPost]publicActionResultCreate(Postpost)
DefaultValueAttributeAgora as ações podem ter valores default, o que antes só era possível com a implementação de diferentes rotas:Agora basta declarar antes do atributoroutes.MapRoute("Default",                                             "{controller}/{action}/{id}",                          new { controller = "Home", action = "Index", id = "" });publicActionResultCreate([DefaultValueAttribute(5)] int pagina)
RequireHttpsAttributePor padrão, as requisições são realizadas com chamadas non-SSL (HTTP)Novo atributo de classe RequireHttpsAttributeque permite direcionar as ações dos controllers para requisições HTTP seguras (SSL-Enabled – HTTPS)28
ProvidersModelMetadata e ModelMetadataProviderA classe ModelMetadataProvider é uma abstração para obter todos os metadados dentro de uma View. Além do provider padrão do MVC para extrair DataAnnotations, é possível criar seus próprios Metadataproviders.
ProvidersModelValidator ProvidersTambém é possível criar seus próprios providers de validação com mapeamentos e regras personalizadasO padrão do MVC também é usando o DataAnnotations.
ExtensibilidadeActionFiltersModel BindersControllerBuilderControllerFactoryControllerControllerActionInvokerViewEngineViewActionResultQualquer parte podesertrocada!
http://www.asp.net/mvc
OpenSource!
http://codeplex.com/aspnet
MindsetNósprecisamos de um controle Repeater!
Nósjá o temos, se chama: laço de foreach.Conversa entre desenvolvedoresdaMicrosoft, segundorelatadopor ScottHanselman, do time do MVC.
O ASP.NET MVC é uma nova opçãoparadesenvolvimento web

[CLPE] Novidades do Asp.net mvc 2

Notas do Editor

  • #4 Estimated Time: 2 minutesFor the entire life of ASP.NET it has been seen as a single framework that included both runtime and presentational aspects. This includes core features such as roles and globalization, as well as WebForms features such as master pages and user controls.
  • #5 Estimated Time: 2 minutesWith the release of .NET Framework 3.5 SP1, ASP.NET started being seen as more modular. ASP.NET Core now represents just the runtime aspects of ASP.NET, and ASP.NET WebForms is simply a presentation option that sits on top of that runtime. With this, it becomes possible to introduce other presentation layer implementations on top of ASP.NET, such as the new ASP.NET MVC framework.While many who are beginning to investigate into ASP.NET MVC think that it is the replacement for WebForms, as you can see, it is simply another option for developing web applications using the ASP.NET runtime.
  • #6 Estimated Time: 1 minuteWebForms has been the only option on the ASP.NET stack and provides a mature product that has proven successful for lots of developers. But it does have some weaknesses.
  • #7 Estimated Time: 2 minutesThe level of abstraction that WebForms provides has a lot of benefits to it, but it doesn’t provide any framework-level guidance in terms of what should do what and when. Between your pages, master pages, user controls, server controls, and custom controls, you can end up with a mixture of HTML, data access code, and business logic.There are certainly methodologies/practices that can be employed with WebForms that can remedy that, but it becomes an implementation task of the developer, since the framework doesn’t provide any of that separation/guidance.
  • #8 Estimated Time: 2 minutesThe control abstractions that WebForms provides are very powerful in that they neatly contain all of the UI and business logic needed so you can just place them within a page and go. The adverse side of that is that it can end up hiding complexity that you’d rather have control over. A common problem is viewstate[Advance Animation]. It isn’t viewstate’s fault that things like this can happen, but it can be very easy to consume a control that could end up hurting the performance of your application.In addition, many times the markup rendered by server controls aren’t always ideal and there is little control over that without having to redo its rendering completely.
  • #9 Estimated Time: 2 minutesMVC is a design pattern that stands for Model-View-Controller. What is strives to do is separate the concerns of an application’s presentation layer by assigning specific roles to the three different components.The Controller is responsible for handling all user input. Once input has been received, the Controller will perform any operations/actions it needs to, which might include interacting with the Model.The Model represents the core concern/logic of the application. Once the Controller retrieves some model data and performs any work with the model/etc it needs to it constructs a presentation model that describes the model in terms the View can understand.The View is the visual representation of the model. It presents the model data to the actual user in a way that is meaningful. In a web application, this would typically be HTML.With these three pieces in place, your presentation layer becomes cleanly separated in such a way that each component can be developed/tested independently.