SlideShare una empresa de Scribd logo
1 de 27
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> } ,[object Object]
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 WebMatrixLa 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=@"{1,4}", month= @"{1,2}", day = @"{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

Más contenido relacionado

La actualidad más candente

Html 5: elementos para mejorar la aparienci
Html 5: elementos para mejorar la aparienciHtml 5: elementos para mejorar la aparienci
Html 5: elementos para mejorar la apariencijcremiro
 
4 Programación Web con .NET y C#
4 Programación Web con .NET y C#4 Programación Web con .NET y C#
4 Programación Web con .NET y C#guidotic
 
Aprendiendo javascript
Aprendiendo javascriptAprendiendo javascript
Aprendiendo javascriptCarlos Salas
 
Sencha touch - Proceso básico de desarrollo
Sencha touch - Proceso básico de desarrolloSencha touch - Proceso básico de desarrollo
Sencha touch - Proceso básico de desarrolloRaúl Jiménez Ortega
 
Comandos basicos para la programación en javascript
Comandos basicos para la programación en javascriptComandos basicos para la programación en javascript
Comandos basicos para la programación en javascriptMicco5W
 

La actualidad más candente (8)

Semana 6 Estructura y Componentes
Semana 6   Estructura y ComponentesSemana 6   Estructura y Componentes
Semana 6 Estructura y Componentes
 
Html 5: elementos para mejorar la aparienci
Html 5: elementos para mejorar la aparienciHtml 5: elementos para mejorar la aparienci
Html 5: elementos para mejorar la aparienci
 
Marcos (1)
Marcos (1)Marcos (1)
Marcos (1)
 
4 Programación Web con .NET y C#
4 Programación Web con .NET y C#4 Programación Web con .NET y C#
4 Programación Web con .NET y C#
 
Aprendiendo javascript
Aprendiendo javascriptAprendiendo javascript
Aprendiendo javascript
 
Sencha touch - Proceso básico de desarrollo
Sencha touch - Proceso básico de desarrolloSencha touch - Proceso básico de desarrollo
Sencha touch - Proceso básico de desarrollo
 
Comandos basicos para la programación en javascript
Comandos basicos para la programación en javascriptComandos basicos para la programación en javascript
Comandos basicos para la programación en javascript
 
Trabajando con css
Trabajando con cssTrabajando con css
Trabajando con css
 

Destacado

HTML5 APIs - Where No Man Has Gone Before - StarTechConf, Chile
HTML5 APIs - Where No Man Has Gone Before - StarTechConf, ChileHTML5 APIs - Where No Man Has Gone Before - StarTechConf, Chile
HTML5 APIs - Where No Man Has Gone Before - StarTechConf, ChileRobert Nyman
 
Multi-QA Environment, parallel development with Git
Multi-QA Environment, parallel development with GitMulti-QA Environment, parallel development with Git
Multi-QA Environment, parallel development with Gitdopejam
 
[500DISTRO] Making Business Go BOOM: The 5 W's of B2B Content Marketing
[500DISTRO] Making Business Go BOOM: The 5 W's of B2B Content Marketing	[500DISTRO] Making Business Go BOOM: The 5 W's of B2B Content Marketing
[500DISTRO] Making Business Go BOOM: The 5 W's of B2B Content Marketing 500 Startups
 
Introducción a las Metodologías Ágiles
Introducción a las Metodologías ÁgilesIntroducción a las Metodologías Ágiles
Introducción a las Metodologías ÁgilesCondiminds
 
FUSE and beyond: bridging filesystems paper by Emmanuel Dreyfus
FUSE and beyond: bridging filesystems paper by Emmanuel DreyfusFUSE and beyond: bridging filesystems paper by Emmanuel Dreyfus
FUSE and beyond: bridging filesystems paper by Emmanuel Dreyfuseurobsdcon
 
Configuration Manager vNext - What to expect
Configuration Manager vNext - What to expectConfiguration Manager vNext - What to expect
Configuration Manager vNext - What to expectTim De Keukelaere
 
Tomcat Maven Plugin
Tomcat Maven PluginTomcat Maven Plugin
Tomcat Maven PluginOlivier Lamy
 
Os 10 Maus Hábitos dos Desenvolvedores JSF
Os 10 Maus Hábitos dos Desenvolvedores JSFOs 10 Maus Hábitos dos Desenvolvedores JSF
Os 10 Maus Hábitos dos Desenvolvedores JSFtarsobessa
 
Caderno SISP 2012
Caderno SISP 2012Caderno SISP 2012
Caderno SISP 2012GovBR
 
SharePoint Search - SPSNYC 2014
SharePoint Search - SPSNYC 2014SharePoint Search - SPSNYC 2014
SharePoint Search - SPSNYC 2014Avtex
 
Static Detection of Application Backdoors
Static Detection of Application BackdoorsStatic Detection of Application Backdoors
Static Detection of Application BackdoorsTyler Shields
 
Reinventing Money BFI Challenge 2015
Reinventing Money BFI Challenge 2015Reinventing Money BFI Challenge 2015
Reinventing Money BFI Challenge 2015SAW Concepts LLC
 
¡This is drupal! - Global Training Days
¡This is drupal! - Global Training Days¡This is drupal! - Global Training Days
¡This is drupal! - Global Training DaysLa Drupalera
 
GlassFish, Maven, Cloud e Java EE
GlassFish, Maven, Cloud e Java EEGlassFish, Maven, Cloud e Java EE
GlassFish, Maven, Cloud e Java EEBruno Borges
 
缓存技术浅谈
缓存技术浅谈缓存技术浅谈
缓存技术浅谈Robbin Fan
 
State of virtualisation -- 2012
State of virtualisation -- 2012State of virtualisation -- 2012
State of virtualisation -- 2012Jonathan Sinclair
 
DBA Basics guide
DBA Basics guideDBA Basics guide
DBA Basics guideazoznasser1
 

Destacado (20)

Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
HTML5 APIs - Where No Man Has Gone Before - StarTechConf, Chile
HTML5 APIs - Where No Man Has Gone Before - StarTechConf, ChileHTML5 APIs - Where No Man Has Gone Before - StarTechConf, Chile
HTML5 APIs - Where No Man Has Gone Before - StarTechConf, Chile
 
Multi-QA Environment, parallel development with Git
Multi-QA Environment, parallel development with GitMulti-QA Environment, parallel development with Git
Multi-QA Environment, parallel development with Git
 
[500DISTRO] Making Business Go BOOM: The 5 W's of B2B Content Marketing
[500DISTRO] Making Business Go BOOM: The 5 W's of B2B Content Marketing	[500DISTRO] Making Business Go BOOM: The 5 W's of B2B Content Marketing
[500DISTRO] Making Business Go BOOM: The 5 W's of B2B Content Marketing
 
Introducción a las Metodologías Ágiles
Introducción a las Metodologías ÁgilesIntroducción a las Metodologías Ágiles
Introducción a las Metodologías Ágiles
 
FUSE and beyond: bridging filesystems paper by Emmanuel Dreyfus
FUSE and beyond: bridging filesystems paper by Emmanuel DreyfusFUSE and beyond: bridging filesystems paper by Emmanuel Dreyfus
FUSE and beyond: bridging filesystems paper by Emmanuel Dreyfus
 
Configuration Manager vNext - What to expect
Configuration Manager vNext - What to expectConfiguration Manager vNext - What to expect
Configuration Manager vNext - What to expect
 
Tomcat Maven Plugin
Tomcat Maven PluginTomcat Maven Plugin
Tomcat Maven Plugin
 
Os 10 Maus Hábitos dos Desenvolvedores JSF
Os 10 Maus Hábitos dos Desenvolvedores JSFOs 10 Maus Hábitos dos Desenvolvedores JSF
Os 10 Maus Hábitos dos Desenvolvedores JSF
 
Caderno SISP 2012
Caderno SISP 2012Caderno SISP 2012
Caderno SISP 2012
 
Visual facilitation for agile BAs
Visual facilitation for agile BAsVisual facilitation for agile BAs
Visual facilitation for agile BAs
 
SharePoint Search - SPSNYC 2014
SharePoint Search - SPSNYC 2014SharePoint Search - SPSNYC 2014
SharePoint Search - SPSNYC 2014
 
Static Detection of Application Backdoors
Static Detection of Application BackdoorsStatic Detection of Application Backdoors
Static Detection of Application Backdoors
 
AngularJS and SPA
AngularJS and SPAAngularJS and SPA
AngularJS and SPA
 
Reinventing Money BFI Challenge 2015
Reinventing Money BFI Challenge 2015Reinventing Money BFI Challenge 2015
Reinventing Money BFI Challenge 2015
 
¡This is drupal! - Global Training Days
¡This is drupal! - Global Training Days¡This is drupal! - Global Training Days
¡This is drupal! - Global Training Days
 
GlassFish, Maven, Cloud e Java EE
GlassFish, Maven, Cloud e Java EEGlassFish, Maven, Cloud e Java EE
GlassFish, Maven, Cloud e Java EE
 
缓存技术浅谈
缓存技术浅谈缓存技术浅谈
缓存技术浅谈
 
State of virtualisation -- 2012
State of virtualisation -- 2012State of virtualisation -- 2012
State of virtualisation -- 2012
 
DBA Basics guide
DBA Basics guideDBA Basics guide
DBA Basics guide
 

Similar a ASP.Net MVC 3 - Eugenio Serrano

Similar a ASP.Net MVC 3 - Eugenio Serrano (20)

Spring Mvc Final
Spring Mvc FinalSpring Mvc Final
Spring Mvc Final
 
Asp.net
Asp.netAsp.net
Asp.net
 
Asp.net
Asp.netAsp.net
Asp.net
 
ASP.NET MVC Workshop Día 1
ASP.NET MVC Workshop Día 1ASP.NET MVC Workshop Día 1
ASP.NET MVC Workshop Día 1
 
Mi app-asp-net-mvc2
Mi app-asp-net-mvc2Mi app-asp-net-mvc2
Mi app-asp-net-mvc2
 
Tutorial3 Desymfony - La Vista. Twig
Tutorial3 Desymfony - La Vista. TwigTutorial3 Desymfony - La Vista. Twig
Tutorial3 Desymfony - La Vista. Twig
 
Web matrix session2
Web matrix session2Web matrix session2
Web matrix session2
 
3. Crear Formularios Web Forms
3.  Crear Formularios Web Forms3.  Crear Formularios Web Forms
3. Crear Formularios Web Forms
 
Curso Jsp Mas
Curso Jsp MasCurso Jsp Mas
Curso Jsp Mas
 
Curso Java Avanzado 3 Js Ps
Curso Java Avanzado   3 Js PsCurso Java Avanzado   3 Js Ps
Curso Java Avanzado 3 Js Ps
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Intro a ASP.NET
Intro a ASP.NETIntro a ASP.NET
Intro a ASP.NET
 
Introducción a ASP.NET
Introducción a ASP.NETIntroducción a ASP.NET
Introducción a ASP.NET
 
[Code Camp 2009] Desarrollando sitios web escalables con ASP.NET MVC (Rodolfo...
[Code Camp 2009] Desarrollando sitios web escalables con ASP.NET MVC (Rodolfo...[Code Camp 2009] Desarrollando sitios web escalables con ASP.NET MVC (Rodolfo...
[Code Camp 2009] Desarrollando sitios web escalables con ASP.NET MVC (Rodolfo...
 
Curso Jsp
Curso JspCurso Jsp
Curso Jsp
 
Javascript
JavascriptJavascript
Javascript
 
ASP.NET MVC - Introducción a ASP.NET MVC
ASP.NET MVC - Introducción a ASP.NET MVCASP.NET MVC - Introducción a ASP.NET MVC
ASP.NET MVC - Introducción a ASP.NET MVC
 
01 Ext Js Introduccion
01 Ext Js   Introduccion01 Ext Js   Introduccion
01 Ext Js Introduccion
 
Arquitectura java web
Arquitectura java webArquitectura java web
Arquitectura java web
 
Tema2a Jsp
Tema2a JspTema2a Jsp
Tema2a Jsp
 

Último

Cortes-24-de-abril-Tungurahua-3 año 2024
Cortes-24-de-abril-Tungurahua-3 año 2024Cortes-24-de-abril-Tungurahua-3 año 2024
Cortes-24-de-abril-Tungurahua-3 año 2024GiovanniJavierHidalg
 
Hernandez_Hernandez_Practica web de la sesion 12.pptx
Hernandez_Hernandez_Practica web de la sesion 12.pptxHernandez_Hernandez_Practica web de la sesion 12.pptx
Hernandez_Hernandez_Practica web de la sesion 12.pptxJOSEMANUELHERNANDEZH11
 
Plan de aula informatica segundo periodo.docx
Plan de aula informatica segundo periodo.docxPlan de aula informatica segundo periodo.docx
Plan de aula informatica segundo periodo.docxpabonheidy28
 
La era de la educación digital y sus desafios
La era de la educación digital y sus desafiosLa era de la educación digital y sus desafios
La era de la educación digital y sus desafiosFundación YOD YOD
 
Proyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptxProyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptx241521559
 
guía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Josephguía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan JosephBRAYANJOSEPHPEREZGOM
 
International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)GDGSucre
 
trabajotecologiaisabella-240424003133-8f126965.pdf
trabajotecologiaisabella-240424003133-8f126965.pdftrabajotecologiaisabella-240424003133-8f126965.pdf
trabajotecologiaisabella-240424003133-8f126965.pdfIsabellaMontaomurill
 
Redes direccionamiento y subredes ipv4 2024 .pdf
Redes direccionamiento y subredes ipv4 2024 .pdfRedes direccionamiento y subredes ipv4 2024 .pdf
Redes direccionamiento y subredes ipv4 2024 .pdfsoporteupcology
 
CLASE DE TECNOLOGIA E INFORMATICA PRIMARIA
CLASE  DE TECNOLOGIA E INFORMATICA PRIMARIACLASE  DE TECNOLOGIA E INFORMATICA PRIMARIA
CLASE DE TECNOLOGIA E INFORMATICA PRIMARIAWilbisVega
 
EPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveEPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveFagnerLisboa3
 
KELA Presentacion Costa Rica 2024 - evento Protégeles
KELA Presentacion Costa Rica 2024 - evento ProtégelesKELA Presentacion Costa Rica 2024 - evento Protégeles
KELA Presentacion Costa Rica 2024 - evento ProtégelesFundación YOD YOD
 
9egb-lengua y Literatura.pdf_texto del estudiante
9egb-lengua y Literatura.pdf_texto del estudiante9egb-lengua y Literatura.pdf_texto del estudiante
9egb-lengua y Literatura.pdf_texto del estudianteAndreaHuertas24
 
Trabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíaTrabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíassuserf18419
 
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricGlobal Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricKeyla Dolores Méndez
 
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...silviayucra2
 

Último (16)

Cortes-24-de-abril-Tungurahua-3 año 2024
Cortes-24-de-abril-Tungurahua-3 año 2024Cortes-24-de-abril-Tungurahua-3 año 2024
Cortes-24-de-abril-Tungurahua-3 año 2024
 
Hernandez_Hernandez_Practica web de la sesion 12.pptx
Hernandez_Hernandez_Practica web de la sesion 12.pptxHernandez_Hernandez_Practica web de la sesion 12.pptx
Hernandez_Hernandez_Practica web de la sesion 12.pptx
 
Plan de aula informatica segundo periodo.docx
Plan de aula informatica segundo periodo.docxPlan de aula informatica segundo periodo.docx
Plan de aula informatica segundo periodo.docx
 
La era de la educación digital y sus desafios
La era de la educación digital y sus desafiosLa era de la educación digital y sus desafios
La era de la educación digital y sus desafios
 
Proyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptxProyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptx
 
guía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Josephguía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Joseph
 
International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)
 
trabajotecologiaisabella-240424003133-8f126965.pdf
trabajotecologiaisabella-240424003133-8f126965.pdftrabajotecologiaisabella-240424003133-8f126965.pdf
trabajotecologiaisabella-240424003133-8f126965.pdf
 
Redes direccionamiento y subredes ipv4 2024 .pdf
Redes direccionamiento y subredes ipv4 2024 .pdfRedes direccionamiento y subredes ipv4 2024 .pdf
Redes direccionamiento y subredes ipv4 2024 .pdf
 
CLASE DE TECNOLOGIA E INFORMATICA PRIMARIA
CLASE  DE TECNOLOGIA E INFORMATICA PRIMARIACLASE  DE TECNOLOGIA E INFORMATICA PRIMARIA
CLASE DE TECNOLOGIA E INFORMATICA PRIMARIA
 
EPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveEPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial Uninove
 
KELA Presentacion Costa Rica 2024 - evento Protégeles
KELA Presentacion Costa Rica 2024 - evento ProtégelesKELA Presentacion Costa Rica 2024 - evento Protégeles
KELA Presentacion Costa Rica 2024 - evento Protégeles
 
9egb-lengua y Literatura.pdf_texto del estudiante
9egb-lengua y Literatura.pdf_texto del estudiante9egb-lengua y Literatura.pdf_texto del estudiante
9egb-lengua y Literatura.pdf_texto del estudiante
 
Trabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíaTrabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnología
 
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricGlobal Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
 
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
 

ASP.Net MVC 3 - Eugenio Serrano

  • 1. ASP.Net MVC 3 Eugenio SerranoSolidQAnalista de Sistemaseserrano@solidq.com
  • 2. ¿Que es Razor? ¿Qué es MVC 3? Usando Modelos, Vistas y Controladores HtmlHelpers y Validadores AJAX en ASP.Net MVC Agenda
  • 3.
  • 4. Permite escribir menos líneas de código
  • 5. Permite mezclar código fuente y códigode marcado de forma mas natural
  • 6. Tiene Helpers que nos ahorran el trabajo
  • 7. Compatible con ASP.NET Web Pages en WebMatrixLa sistaxis de Razor
  • 8. 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):
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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>
  • 13. 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>
  • 14. 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>
  • 15. Motor de vistas RAZOr Demostración
  • 16. 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
  • 17. ¿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
  • 18. Viewstate en webforms y mvc Demostración
  • 20. ¿Como funciona? Controller Controlador: Recupera el modelo. Hace cosas. Request View Vista: Genera una representaciónvisual del modelo Response
  • 22. 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
  • 23. 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=@"{1,4}", month= @"{1,2}", day = @"{1,2}"}); }
  • 24. 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); } }
  • 25. 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.
  • 26. ASP.NET MVC 3 Demostración
  • 27. 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
  • 28. ASP.NET MVC 3 y AJAX Demostración
  • 29. 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
  • 30. 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.
  • 31. Preguntas ? Eugenio SerranoSolidQAnalista de Sistemaseserrano@solidq.com

Notas del editor

  1. 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. 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.
  3. 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 &lt;div&gt; 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 &lt;text&gt; 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.
  4. 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.
  5. 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&apos;t include any actual content. After you&apos;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.
  6. 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 &lt;p&gt; 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..
  7. 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(&quot;header&quot;, required: false)http://www.asp.net/webmatrix/tutorials/3-creating-a-consistent-look
  8. 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.
  9. See demo script for details
  10. See demo script for details
  11. 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.
  12. 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.
  13. See demo script for details
  14. See demo script for details
  15. 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.
  16. 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 &lt;% %&gt; 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.