ASP.Net MVC 3 - Eugenio Serrano


Published on

Presentacion de Eugenio Serrano, en el WebCamp de Cordoba, Argentina, Mayo 2011

Published in: Technology
1 Comment
1 Like
  • It is in point of fact a nice and helpful piece of information. I’m satisfied that you just shared this helpful information with us. Please keep us informed like this.
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Note – only use this slide if you are using ASP.NET MVC 3With ASP.NET MVC 3 we’ve added a new view engine which uses a new lightweight syntax called Razor. Razor is designed to make it easier and faster to write code and allows you to mix markup and code for more understandable views. The new syntax is characterized by the new @ symbol that you will see commonly in Razor views and allows you to mix code and markup freely, which makes for much cleaner code.Razor also allows you to make use of “Helpers” which are shortcuts that make it easier to use common plugins like ReCapture, Facebook Social Plugins, OData etc.The Razor syntax is actually borrowed from the younger sibling of MVC, ASP.NET Web Pages, with a few modifications that are added on top. For example MVC adds the @model keyword so that you no longer have to specify the full namespace in your directive when you are referencing models or ViewModels.
  • 2 minutesWe’ve designed Razor to be super concise and easy to use. When we think about the way developers use a language we take into account the context switching they have to do and also the number of keystrokes. The way that Razor allows you to transition seamlessly between markup and code makes for a much more natural and fluent style and also helps to reduce the number of keystrokes and context switching that a developer has to do, thinking about markup and code separately. With Razor, markup and code are really the same thing.We think it’s the easiest way to code websites and when you compare it to the other languages out there, it’s easy to see why.
  • 1 minuteThe transition from code to markup is one of the most elegant things about Razor but there a few rules that are worth knowing about. Option 1:Code is the primary citizen in a code block, not HTML. This means the parser will always expect code unless it finds valid opening (and closing) tags. In the first option block you see that after the @{ a name variable is defined. No additional tag is necessary. A <div> section tells Razor that what follows should be taken as literal. Then the @name indicates a variable that needs to be replaced with its value.Option 2:Similarly, to explicitly call out text in a code block as HTML, wrap it in a <text> tagOption 3:Single line of output within markup can be denoted by @:This option is useful when you don’t want to render an HTML element as part of the output. Extra Knowledge (Advanced):The Parser that understands Razor is itself a standalone assembly (System.Web.Razor.dll) that has no dependencies on ASP.NET, which means you can use it to parse CSHTML/VBHTML files and produce C#/VB code in any .NET application.
  • 1 minuteIt’s always good practice to comment your code. In Razor we have the following options for commenting:Option 1:You can comment a block by using @* … *@Please note that this method could not be recursive (you could not have a @* inside another @*)Option 2:You can comment lines by using // (in C#) the same way you do in your code files.Option 3:If you need to comment a whole razor block, you should add a @* before the beginning of the code block and a *@ after it’s finish.
  • 1 minuteThe bigger your site, the more pages you’ll have. One thing to keep in mind when building websites is how it will be navigated by users. The content usually changes from one page to the other, but the structure of the site, its menu, links, images, remain constant across all pages. As you add new pages and functionality, chances are that you find yourself repeating the same markup (HTML) , copy and pasting code across multiple pages to keep this consistency, and having to make changes everywhere every time you want to change the appearance of the website, etc.Here is were layouts come to the rescue!Layoutpages allow you to organize commonly used markup and code into one file and then reuse it across multiple pages on your website. They are pages that contain HTML-formatted content that can be shared by pages on the website. A layout page defines the structure of the web page, but doesn't include any actual content. After you've created a layout page, you can create web pages with content and then link them to the layout page. When these pages are displayed, they will be formatted according to the layout page.
  • 1 minuteIn order to use Layout pages you have to:Define the layout pageReference it in your pages.1. In this sample, we define an html section containing a header, a title and then a block for the body: @RenderBody()2.Then in MyPage we reference the layout page and then add a content in a <p> paragraph.This results in a page that contains the structure of _Layout and the content defined in MyPage. This will allow you to have all the common content and graphic layout in the _Layout page, and when needed, making layout changes in one place only..
  • 1 minuteThink ofRenderBody as rendering an unnamed or default section in your page. We can also add named sections too for content which we often expect to see in our pages. A good example is a header or a menu which might change based on the visited page. All the logic to create this menu depending on who is logged on, and how to create it, (e.g: using graphic files and hyperlinks) could be in a separated file.Normally, the sections that you create in a content page have to match the sections that are defined in the layout page. You can override this behavior for a named section by declaring the section to be optional in the layout page. This lets you define multiple content pages that can be shared. To do this, in the layout file change the render of a section adding a “required: false” parameter@RenderSection("header", required: false)
  • Sometimes you find content and code that doesn’t change, for instance: header and footer. They remain the same across all your site. To do this, you can use the @RenderPage command.
  • See demo script for details
  • See demo script for details
  • 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 data in the application. Once the Controller retrieves some model data and performs any work with the model, 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.
  • Estimated Time: 4 minutesSo what does MVC look like when implemented over the web?When an HTTP request comes into the application it is mapped to a controller. Remember as we mentioned in the previous slide, in the MVC design pattern, the controller is the piece of the triad that handles all user input. In the case of a web application, user input is represented as HTTP requests [Advance Animation].Once the controller has received input, it performs whatever operations it needs to and then assembles a presentation model [Advance Animation].The controller then takes the model and passes it off to the view. Remember that the view is simply a visual representation of the model [Advance Animation].The view then “transforms” the model into whatever format it uses to represent it. In a web application, this would typically be HTML [Advance Animation].The view then serves the request by responding with its visual representation.
  • See demo script for details
  • See demo script for details
  • 2 minutesWhen we look at all the different profiles of people creating websites we see certain patterns emerge. First, there is a group of people that want to easily create simple web sites to share information about their hobbies, work, to share photos, and so on. Web Apps are overkills for them. They just need to get the site up and running rapidly from scratch.There’s another group of people that like to use the large number of rich web applications out there as a starting point, they need to get to a solution quickly and in an easy way. Many of this web apps are tailored for specific tasks, and provide 80% of the functionality of a solution; the developer just need to customize them and publish them.Finally, there are the professional developers that need to build complex and scalable web sites. For this, they need tools that help them work in a team, source and version control, a testing framework, and tools with lots of powerful extensions.
  • Estimated Time: 2 minutesNo matter which type of developer you are, you get the benefit of the ASP.NET Core runtime, which provides many useful modules that provide functionality that you are likely to need when creating web applications. For example: Profile, Roles and Membership is important if you want to build in users and security around different parts of your website.[Build x 3]ASP.NET Web Forms, ASP.NET MVC and ASP.NET Web Pages are three different approaches to building web applications on the server side with ASP.NET. They all build on top of the same core runtime that provides them with the same powerful set of modules that web developers can leverage from within their web applications. ASP.NET Web Forms is great for developers coming from desktop application development where they are accustomed to controls, event-driven development and code-behind. Despite not being concepts that are native to the web, Web Forms achieves this by abstracting away things like maintaining state, form posting and much more. This ease of development means that developers relinquish a certain amount of control as Web Forms manages communication between the server and client on your behalf.ASP.NET MVC, in contrast, is for developers that like to be in full control of the interactions between client and server and provides a more “raw” approach to what happens in the web application. Due to its loosely coupled architecture, MVC is also very extensible with many places for developers to customize and plugin components as well write test code easily.Developing in ASP.NET Web Pages is centered around inline code and is similar to PHP or classic ASP in that compilation of your application isn’t required (it is in WebForms and MVC). It is designed to provide the simplest approach to building websites with the fewest number of concepts to learn.[Build x 2]When it comes to controlling the markup that is rendered to the client there are two view engines you may use. The Web Forms view engine is shared by both Web Forms and MVC and uses the familiar <% %> syntax. With ASP.NET MVC 3 and ASP.NET Web Pages Microsoft introduced the Razor View Engine which uses a different syntax centered around the @ symbol. The Razor syntax uses fewer characters to achieve the same things in Web Forms and allows the developer to mix markup and code really easily.
  • ASP.Net MVC 3 - Eugenio Serrano

    1. 1. ASP.Net MVC 3<br />Eugenio SerranoSolidQAnalista de<br />
    2. 2. ¿Que es Razor?<br />¿Qué es MVC 3?<br />Usando Modelos, Vistas y Controladores<br />HtmlHelpers y Validadores<br />AJAX en ASP.Net MVC<br />Agenda<br />
    3. 3. @if (User.Grok(Razor)) {<br /> <div>w00t!</div><br />}<br /><ul><li>Nuevo motor de vistas mucho más simple
    4. 4. Permite escribir menos líneas de código
    5. 5. Permite mezclar código fuente y códigode marcado de forma mas natural
    6. 6. Tiene Helpers que nos ahorran el trabajo
    7. 7. Compatible con ASP.NET Web Pages en WebMatrix</li></ul>La sistaxis de Razor<br />
    8. 8. Razor comparado con el resto<br />Web Forms (6 transiciones):<br /><ul><br /><% for (int i = 0; i < 10; i++) { %><br /> <li><% =i %></li><br /><% } %><br /></ul><br /><ul><br /><?php<br />for ($i = 0; $i < 10; $i++) {<br />echo("<li>$i</li>");<br /> } <br /> ?><br /></ul><br />PHP(2 transicionesy 1 echo):<br /><ul><br />@for (int i = 0; i < 10; i++) {<br /> <li>@i</li><br /> }<br /></ul><br />Razor (2 transiciones):<br />
    9. 9. Generando markup desde el código<br />@{<br />var name = “John Doe”;<br /> <div><br /> Your name: @name<br /> </div><br />}<br />Opción 1:<br />HTML Block<br />@{<br />var name = “John Doe”;<br /> <text><br /> Your name: @name<br /> </text><br />}<br />Opción 2:<br />Text Block<br />@{<br />var name = “John Doe”;<br /> @: Your name: @name<br />}<br />Opción 3:<br />Una simple lineade salida<br />
    10. 10. Comentarios en Razor<br />@*<br /> <div><br /> Hello World<br /> </div><br />*@<br />Opción 1:<br />Markup<br />@{ <br /> //var name = "John Doe”;<br /> //@name<br />}<br />Opción 2:<br />Codigo<br />@*<br /> @{ <br />var name = "John Doe";<br /> @name<br /> }<br />*@<br />Opción 3:<br />Ambos<br />
    11. 11. No escriba 2 veces lo mismo!<br />Defina 1 layout y uselo en todo el sitio<br />Layouts para organizar páginas<br />Page 1<br />Layout.cshtml<br />Page 2<br />Page 3<br />
    12. 12. Defina su Layout<br />Referéncielos en sus paginas<br />Sintaxis de los Layouts<br />/Shared/_Layout.cshtml<br /><html><br />    <head><br />      <title>Simple Layout</title><br />    </head><br />    <body> <br />        @RenderBody()<br /> </body><br /></html><br />MyPage.cshtml<br />@{ <br /> Layout = "/Shared/_Layout.cshtml";<br />}<br /><p><br /> My content goes here<br /></p><br />
    13. 13. Sections permiten definir aéreas de contenido que cambian entre paginas pero necesitan ser incluidas en el Layout<br />Sections para organizar las páginas<br />/Shared/_Layout.cshtml<br />MyPage.cshtml<br /><html><br />    <head><br />      <title>Simple Layout</title><br />    </head><br />    <body> <br />@RenderSection("Menu")<br />        @RenderBody()<br /> </body><br /></html><br />@{ <br /> Layout = "/Shared/_Layout.cshtml";<br />}<br />@section Menu {<br /> <ulid="pageMenu"><br /><li>Option 1</li><br /><li>Option 2</li><br /> </ul><br />}<br /><p><br /> My content goes here<br /></p><br />
    14. 14. RenderPage() lo ayuda a reusar markup y código que no cambia<br />Use RenderPage para organizarporciones que no cambian<br />/Shared/_Layout.cshtml<br />/Shared/_Footer.cshtml<br /><html><br />    <head><br />      <title>Simple Layout</title><br />    </head><br />    <body> <br /> @RenderSection("Menu")<br />        @RenderBody()<br />@RenderPage("/Shared/_Footer.cshtml")<br /> </body><br /></html><br /><div class="footer"><br />   © 2010 Contoso<br /></div><br />
    15. 15. Motor de vistas RAZOr<br />Demostración<br />
    16. 16. ASP.NET MVC<br />Un nuevo framework para desarrollo Web<br />Más control sobre el HTML<br />Más fácil de hacer test<br />Puede usar Web Forms o RAZOR para generar el HTML<br />Esta construido sobre en ASP.NET<br />
    17. 17. ¿Que ofrece?<br />SoC (Separation of Concerns)<br />TDD por default<br />Mantenibilidad<br />Url y HTML mas limpio<br />SEO y REST friendly<br />/Clientes/Buscar/Eugenio<br />CSS Friendly<br /><html> <div> <label> <span><br />Modelo de programación mas performante<br />No hay ViewState<br />No hay modelo de eventos<br />
    18. 18. Viewstate en webforms y mvc<br />Demostración<br />
    19. 19. ¿Como funciona?<br />
    20. 20. ¿Como funciona?<br />Controller<br />Controlador:<br />Recupera el modelo.<br />Hace cosas.<br />Request<br />View<br />Vista:<br />Genera una representaciónvisual del modelo<br />Response<br />
    21. 21. Rutas<br /><br />
    22. 22. URLs amigables<br />Legibles<br /><br /><br />Predecibles<br /><br />
    23. 23. Ruteo – URIs amigables<br />Se agregan rutas a la RouteTable global<br />El Mapeo crea un objeto RouteData (un diccionario de key/values)<br />protectedvoidApplication_Start(objectsender, EventArgs e) {<br />RouteTable.Routes.Add(<br /> "Blog/bydate/[year]/[month]/[day]",<br /> new { controller="blog", action="showposts" },<br /> new { year=@"d{1,4}", month= @"d{1,2}", day = @"d{1,2}"});<br />} <br />
    24. 24. Controlador – Uso Básico<br />Escenarios, Objetivos y Diseño<br />Las URLs indican “acciones” del Controlador, no páginas<br />Las acciones deben declarase en el Controlador.<br />El controlador ejecuta lógica y elige la vista.<br />publicActionResultShowPost(int id) {<br /> Post p = PostRepository.GetPostById(id);<br />if (p != null) {<br /> View(p);<br /> } else {<br /> View("nosuchpost", id);<br /> }<br />}<br />
    25. 25. Vistas – Uso Básico<br />Escenarios, Objetivos y Diseño:<br />Generan HTML u otro tipo de contenido. <br />Helperspre-definidos.<br />Pueden ser WebForms o Razor (u otras)<br />Formatos de salida (images, RSS, JSON, …).<br />Pueden definirse vistas Mock para testing.<br />El controlador ofrece datos a la Vista<br />Datos Looselytypedo Stronglytyped.<br />
    26. 26. ASP.NET MVC 3 <br />Demostración<br />
    27. 27. AJAX en ASP.Net MVC<br />UnobstructiveAjax<br />Evita mezclar código script con código HTML<br />Basado en jQuery<br />En MVC 3, se han portado todas las librerías de script a jQuery<br />Validadores remotos<br />
    28. 28. ASP.NET MVC 3 y AJAX<br />Demostración<br />
    29. 29. ASP.NET: Un Framework paratodo<br />Quiero crear sitios por mi cuenta para aprender a usar una herramienta y conocer un framework de forma fácil<br />Soy un desarrollador profesional y construyo grandes (y complejos) sitios web junto a un grupo desarrolladores<br />Mantengo menos de<br />3 Web Apps. Necesito una herramienta que sea fácil de usar, de configurar, y poder publicar mis sitios fácilmente<br />
    30. 30. ASP.NET: Un Framework paratodo<br />WebMatrix<br />Visual Studio 2010<br />ASP.NET Core<br />Web Forms View Engine<br />Razor View Engine<br />Modules<br />Globalization<br />Caching<br />Controls<br />Pages<br />Master Pages<br />Profile<br />Roles<br />Membership<br />ASP.NET <br />Web Pages<br />ASP.NET <br />Web Forms<br />ASP.NET <br />MVC<br />Intrinsics<br />Handlers<br />Etc.<br />
    31. 31. Preguntas ?<br />Eugenio SerranoSolidQAnalista de<br />