ASP.Net MVC 3 - Eugenio Serrano
Upcoming SlideShare
Loading in...5
×
 

ASP.Net MVC 3 - Eugenio Serrano

on

  • 7,135 views

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

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

Statistics

Views

Total Views
7,135
Views on SlideShare
5,688
Embed Views
1,447

Actions

Likes
1
Downloads
95
Comments
11

4 Embeds 1,447

http://www.eugenioserrano.com.ar 1440
http://webcache.googleusercontent.com 3
http://paper.li 3
http://translate.googleusercontent.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

110 of 11 Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • instant payday loans canada is available in my site so check now
    Are you sure you want to
    Your message goes here
    Processing…
  • uk payday loans is given with more information in my site. check it
    Are you sure you want to
    Your message goes here
    Processing…
  • healtjh insurance online is accessible in my site with a lots of information. Visit now.
    Are you sure you want to
    Your message goes here
    Processing…
  • order cheap medicine in my site and gather more information about it.
    Are you sure you want to
    Your message goes here
    Processing…
  • I offer cash advances in my site so have a time to visit now.
    Are you sure you want to
    Your message goes here
    Processing…

110 of 11

Post Comment
Edit your comment
  • 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 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 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 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)http://www.asp.net/webmatrix/tutorials/3-creating-a-consistent-look
  • 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 ASP.Net MVC 3 - Eugenio Serrano Presentation Transcript

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