SlideShare a Scribd company logo
1 of 25
Introducción
ASP.NET MVC.
Mauricio Alfonso Prieto
Contenido
▪ Que es MVC.
▪ ASP.NET MVC.
▪ Web Pages Applications
▪ Web Forms Applications.
▪ MVC Applications.
▪ MVC Models (Entity Framework).
▪ MVC Controllers.
▪ MVC Views.
Modelo–vista–controlador
▪ El modelo–vista–controlador (MVC) es un patrón de arquitectura de software que
separa los datos y la lógica de negocio de una aplicación de la interfaz de
usuario y el módulo encargado de gestionar los eventos y las comunicaciones.
ASP.NET MVC
▪ El ASP.NET MVC Framework es un framework de aplicaciones web que
implementa el patrón modelo-vista-controlador (MVC).
Browser
Controller
View Model
Database
Web Server HTTP
SQL
Modelos, Vistas y Controladores
▪ Web Matrix ó Visual Studio
▪ Código en archivos .CSHTML (.VBHTML) *Razor
▪ Control Preciso del HTML
Web Pages Applications
<h2>Special Offers</h2>
<p>Get the best possible value on Northwind specialty
foods by taking advantage of these offers:</p>
@foreach (var item in offers) {
<div class="offer-card">
<div class="offer-picture">
@if (!String.IsNullOrEmpty(item.PhotoUrl)){
<img src="@Href(item.PhotoUrl) alt="@item.Title" />
}
</div>
</div>
}
Web Forms Applications
▪ Unicamente Visual Studio
▪ Código en archivos .aspx y archivos code-behind **
▪ Crear una interfaz de usuario arrastrando los controles en una página
▪ Controles proporcionan muchas propiedades y eventos
▪ Bind controls para data
MVC Applications
▪ Modelos encapsulan objetos y datos
▪ Vistas generan la interfaz de usuario
▪ Controladores interactúan con las acciones del usuario
▪ Sólo Visual Studio
▪ Código en archivos .cshtml y .cs
▪ El control preciso de HTML y direcciones URL
MVC Models
Desarrollando Modelos
-PhotoID : int
-Title : string
-PhotoFile : byte
-Description : string
-CreatedDate : object
-Owner : string
Photo
-CommentID : int
-User : string
-Subject : string
-Body : string
-PhotoID : int
Comment
1 0..*
public class Photo
{
public int PhotoID { get; set; }
public string Title { get; set; }
public byte[] PhotoFile { get; set; }
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
public string Owner { get; set; }
public virtual List<Comment> Comments { get; set; }
}
Data Annotations
public class Photo
{
// other properties excluded
[DisplayName("Picture")]
public byte[] PhotoFile { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[DataType(DataType.DateTime)]
[DisplayName("Created Date")]
[DisplayFormat(DataFormatString =
"{0:dd/MM/yy}"]
public DateTime CreatedDate { get; set; }
}
Validaciones de usuario con Data Annotations
public class Person
{
public int PersonID { get; set; }
[Required(ErrorMessage="Please enter a name.")]
public string Name { get; set; }
[Range(0, 400)]
public int Height { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string EmailAddress { get; set; }
}
Acceso a datos en modelos y repositorios
Model
Database
Model
Database
Repository
MVC Controller
▪ Crear método público
▪ Devuelve una clase que deriva de ActionResult
▪ Agregar parámetros al método
▪ Escribe el código para realizar la operación y devolver el resultado
Escribir una acción de controlador incluye :
public ActionResult GetSessionByTitle(string title){
var query = from s in context.Sessions
where s.Title == title
select s
Photo session = query.FirstOrDefault();
return View("Details", session);
}
http://www.adventureworks.com/session/getsessionbytitle?title=MVC101
DefaultModelBinder
Pasando datos a la Vista
▪ Modelo
▪ Ver (datos )
▪ Inflexible de tipos , puede ser más flexible
▪ Más complejo
▪ ViewBag
▪ Objeto dinámico para el almacenamiento de piezas básicas de información
▪ Alias para ViewData
▪ Perfecto para el envío de mensajes a la vista
▪ Sólo está disponible para que la acción
▪ Redirecciones causar la ViewBag que ser vaciado
▪ TempData
▪ Al igual que el ViewBag , pero también está disponible en la siguiente página
MVC Views
Ejemplo de vista con Razor
@* Some more Razor examples *@
<span>
Price including Sale Tax: @Model.Price * 1.2
</span>
<span>
Price including Sale Tax: @(Model.Price * 1.2)
</span>
@if (Model.Count > 5)
{
<ol>
@foreach(var item in Model)
{
<li>@item.Name</li>
}
</ol>
}
Direnenciar código del server desde HTML
▪ Razor identifica el código del lado del servidor , buscando el símbolo @ .
▪ En sintaxis Razor , el símbolo @ tiene varios usos . Usted puede :
▪ Use @ para identificar el lado del servidor de C # código
▪ Use @@para rendir un símbolo @ en una página HTML .
▪ Utilice @ : declarar explícitamente una línea de texto como el contenido y no el código .
▪ Utilice < texto > para declarar explícitamente varias líneas de texto como el
contenido y no el código .
▪ Para hacer que el texto sin codificación HTML , puede utilizar el helper Html.Raw
( ) .
HTML Helpers
▪ Action Helpers
▪ Display Helpers
▪ The Begin Form Helper
▪ Editor Helpers
▪ Validation Helpers
Action Helpers
• Html.ActionLink()
• Url.Action()
@Html.ActionLink("Click here to view photo 1",
"Display", new { id = 1 })
<a href="/photo/display/1">
Click here to view photo 1
</a>
<img alt="This image came from an action"
src="@Url.Action("GetImage", new { id = 1 })" />
<img
alt="This image came from an action"
src="/photo/getimage/1" })"
/>
Display Helpers
• Html.DisplayNameFor()
• Html.DisplayFor()
@Html.DisplayNameFor(model => model.CreatedDate)
@Html.DisplayFor(model => model.CreatedDate)
Created Date
03/12/2012
The Begin Form Helper
Html.BeginForm()
@using (Html.BeginForm("Create", "Photo",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@* Place input controls here *@
}
<form action="/Photo/Create" method="post“
enctype="multipart/form-data">
</form>
Editor Helpers
Html.LabelFor()
Html.EditorFor()
@Html.LabelFor(model => model.ContactMe)
@Html.EditorFor(model => model.ContactMe)
<label for="ContactMe">
Contact Me
</label>
<input type="checkbox"
name="Description">
Validation Helpers
Html.ValidationSummary()
Html.ValidationMessageFor()
@Html.ValidationSummary()
@Html.ValidationMessageFor(model => model.Email)
<ul>
<li>Please enter your last name</li>
<li>Please enter a valid email address</li>
</ul>
Please enter a valid email address

More Related Content

Viewers also liked

Network developer company report
Network developer company reportNetwork developer company report
Network developer company reportrindbaloch
 
Interculturality Castelli
Interculturality CastelliInterculturality Castelli
Interculturality Castellirominabaez
 
Fennoskandia Pekka Kivikas
Fennoskandia Pekka KivikasFennoskandia Pekka Kivikas
Fennoskandia Pekka KivikasRockArtKivikas
 
Hezkuntzaren altxor ezkutua
Hezkuntzaren altxor ezkutuaHezkuntzaren altxor ezkutua
Hezkuntzaren altxor ezkutuaIzar Verhorst
 
Ejercicios mate iii
Ejercicios mate iiiEjercicios mate iii
Ejercicios mate iiiyamel02
 
Vision ontoepistemica carlos suarez
Vision ontoepistemica carlos suarez Vision ontoepistemica carlos suarez
Vision ontoepistemica carlos suarez Carlos Suarez
 
Audience Theory
Audience TheoryAudience Theory
Audience TheoryktDan
 
ANCILLARY TEXT: Digipak Elements
ANCILLARY TEXT: Digipak Elements ANCILLARY TEXT: Digipak Elements
ANCILLARY TEXT: Digipak Elements ktDan
 
Evaluation of-total-quality-management-implementation-as-engineering-practice...
Evaluation of-total-quality-management-implementation-as-engineering-practice...Evaluation of-total-quality-management-implementation-as-engineering-practice...
Evaluation of-total-quality-management-implementation-as-engineering-practice...Ali Salah
 
Connectivist Learning Theory
Connectivist Learning TheoryConnectivist Learning Theory
Connectivist Learning TheoryCath Farrant
 
SWOT VE PEST ANALİZİ - ÜLKER / YILDIZ HOLDİNG
SWOT VE PEST ANALİZİ - ÜLKER / YILDIZ HOLDİNGSWOT VE PEST ANALİZİ - ÜLKER / YILDIZ HOLDİNG
SWOT VE PEST ANALİZİ - ÜLKER / YILDIZ HOLDİNGFurkan Özgür
 

Viewers also liked (12)

Network developer company report
Network developer company reportNetwork developer company report
Network developer company report
 
Interculturality Castelli
Interculturality CastelliInterculturality Castelli
Interculturality Castelli
 
Fennoskandia Pekka Kivikas
Fennoskandia Pekka KivikasFennoskandia Pekka Kivikas
Fennoskandia Pekka Kivikas
 
Hezkuntzaren altxor ezkutua
Hezkuntzaren altxor ezkutuaHezkuntzaren altxor ezkutua
Hezkuntzaren altxor ezkutua
 
Ejercicios mate iii
Ejercicios mate iiiEjercicios mate iii
Ejercicios mate iii
 
Vision ontoepistemica carlos suarez
Vision ontoepistemica carlos suarez Vision ontoepistemica carlos suarez
Vision ontoepistemica carlos suarez
 
Animation
AnimationAnimation
Animation
 
Audience Theory
Audience TheoryAudience Theory
Audience Theory
 
ANCILLARY TEXT: Digipak Elements
ANCILLARY TEXT: Digipak Elements ANCILLARY TEXT: Digipak Elements
ANCILLARY TEXT: Digipak Elements
 
Evaluation of-total-quality-management-implementation-as-engineering-practice...
Evaluation of-total-quality-management-implementation-as-engineering-practice...Evaluation of-total-quality-management-implementation-as-engineering-practice...
Evaluation of-total-quality-management-implementation-as-engineering-practice...
 
Connectivist Learning Theory
Connectivist Learning TheoryConnectivist Learning Theory
Connectivist Learning Theory
 
SWOT VE PEST ANALİZİ - ÜLKER / YILDIZ HOLDİNG
SWOT VE PEST ANALİZİ - ÜLKER / YILDIZ HOLDİNGSWOT VE PEST ANALİZİ - ÜLKER / YILDIZ HOLDİNG
SWOT VE PEST ANALİZİ - ÜLKER / YILDIZ HOLDİNG
 

Similar to Introducción mvc

Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
ASP.NET 4 and AJAX
ASP.NET 4 and AJAXASP.NET 4 and AJAX
ASP.NET 4 and AJAXKulveerSingh
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCSunpawet Somsin
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc trainingicubesystem
 
331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheet331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheetstephen972973
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Introduction To ASP.NET MVC
Introduction To ASP.NET MVCIntroduction To ASP.NET MVC
Introduction To ASP.NET MVCAlan Dean
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...SharePoint Saturday NY
 
Microsoft and jQuery: A true love story - templating and other contributions
Microsoft and jQuery: A true love story - templating and other contributionsMicrosoft and jQuery: A true love story - templating and other contributions
Microsoft and jQuery: A true love story - templating and other contributionsjamessenior
 
Intro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersIntro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersFrank La Vigne
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introductionTomi Juhola
 
Building an Angular 2 App
Building an Angular 2 AppBuilding an Angular 2 App
Building an Angular 2 AppFelix Gessert
 

Similar to Introducción mvc (20)

Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
Asp.Net MVC 5 in Arabic
Asp.Net MVC 5 in ArabicAsp.Net MVC 5 in Arabic
Asp.Net MVC 5 in Arabic
 
ASP.NET 4 and AJAX
ASP.NET 4 and AJAXASP.NET 4 and AJAX
ASP.NET 4 and AJAX
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheet331592291-HTML-and-Cascading style sheet
331592291-HTML-and-Cascading style sheet
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
Introduction To ASP.NET MVC
Introduction To ASP.NET MVCIntroduction To ASP.NET MVC
Introduction To ASP.NET MVC
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
 
Microsoft and jQuery: A true love story - templating and other contributions
Microsoft and jQuery: A true love story - templating and other contributionsMicrosoft and jQuery: A true love story - templating and other contributions
Microsoft and jQuery: A true love story - templating and other contributions
 
Intro to MVC 3 for Government Developers
Intro to MVC 3 for Government DevelopersIntro to MVC 3 for Government Developers
Intro to MVC 3 for Government Developers
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
php
phpphp
php
 
Building an Angular 2 App
Building an Angular 2 AppBuilding an Angular 2 App
Building an Angular 2 App
 

Recently uploaded

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 

Recently uploaded (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 

Introducción mvc

  • 2. Contenido ▪ Que es MVC. ▪ ASP.NET MVC. ▪ Web Pages Applications ▪ Web Forms Applications. ▪ MVC Applications. ▪ MVC Models (Entity Framework). ▪ MVC Controllers. ▪ MVC Views.
  • 3. Modelo–vista–controlador ▪ El modelo–vista–controlador (MVC) es un patrón de arquitectura de software que separa los datos y la lógica de negocio de una aplicación de la interfaz de usuario y el módulo encargado de gestionar los eventos y las comunicaciones. ASP.NET MVC ▪ El ASP.NET MVC Framework es un framework de aplicaciones web que implementa el patrón modelo-vista-controlador (MVC).
  • 4. Browser Controller View Model Database Web Server HTTP SQL Modelos, Vistas y Controladores
  • 5. ▪ Web Matrix ó Visual Studio ▪ Código en archivos .CSHTML (.VBHTML) *Razor ▪ Control Preciso del HTML Web Pages Applications <h2>Special Offers</h2> <p>Get the best possible value on Northwind specialty foods by taking advantage of these offers:</p> @foreach (var item in offers) { <div class="offer-card"> <div class="offer-picture"> @if (!String.IsNullOrEmpty(item.PhotoUrl)){ <img src="@Href(item.PhotoUrl) alt="@item.Title" /> } </div> </div> }
  • 6. Web Forms Applications ▪ Unicamente Visual Studio ▪ Código en archivos .aspx y archivos code-behind ** ▪ Crear una interfaz de usuario arrastrando los controles en una página ▪ Controles proporcionan muchas propiedades y eventos ▪ Bind controls para data
  • 7. MVC Applications ▪ Modelos encapsulan objetos y datos ▪ Vistas generan la interfaz de usuario ▪ Controladores interactúan con las acciones del usuario ▪ Sólo Visual Studio ▪ Código en archivos .cshtml y .cs ▪ El control preciso de HTML y direcciones URL
  • 9. Desarrollando Modelos -PhotoID : int -Title : string -PhotoFile : byte -Description : string -CreatedDate : object -Owner : string Photo -CommentID : int -User : string -Subject : string -Body : string -PhotoID : int Comment 1 0..* public class Photo { public int PhotoID { get; set; } public string Title { get; set; } public byte[] PhotoFile { get; set; } public string Description { get; set; } public DateTime CreatedDate { get; set; } public string Owner { get; set; } public virtual List<Comment> Comments { get; set; } }
  • 10. Data Annotations public class Photo { // other properties excluded [DisplayName("Picture")] public byte[] PhotoFile { get; set; } [DataType(DataType.MultilineText)] public string Description { get; set; } [DataType(DataType.DateTime)] [DisplayName("Created Date")] [DisplayFormat(DataFormatString = "{0:dd/MM/yy}"] public DateTime CreatedDate { get; set; } }
  • 11. Validaciones de usuario con Data Annotations public class Person { public int PersonID { get; set; } [Required(ErrorMessage="Please enter a name.")] public string Name { get; set; } [Range(0, 400)] public int Height { get; set; } [Required] [DataType(DataType.EmailAddress)] public string EmailAddress { get; set; } }
  • 12. Acceso a datos en modelos y repositorios Model Database Model Database Repository
  • 14. ▪ Crear método público ▪ Devuelve una clase que deriva de ActionResult ▪ Agregar parámetros al método ▪ Escribe el código para realizar la operación y devolver el resultado Escribir una acción de controlador incluye :
  • 15. public ActionResult GetSessionByTitle(string title){ var query = from s in context.Sessions where s.Title == title select s Photo session = query.FirstOrDefault(); return View("Details", session); } http://www.adventureworks.com/session/getsessionbytitle?title=MVC101 DefaultModelBinder
  • 16. Pasando datos a la Vista ▪ Modelo ▪ Ver (datos ) ▪ Inflexible de tipos , puede ser más flexible ▪ Más complejo ▪ ViewBag ▪ Objeto dinámico para el almacenamiento de piezas básicas de información ▪ Alias para ViewData ▪ Perfecto para el envío de mensajes a la vista ▪ Sólo está disponible para que la acción ▪ Redirecciones causar la ViewBag que ser vaciado ▪ TempData ▪ Al igual que el ViewBag , pero también está disponible en la siguiente página
  • 18. Ejemplo de vista con Razor @* Some more Razor examples *@ <span> Price including Sale Tax: @Model.Price * 1.2 </span> <span> Price including Sale Tax: @(Model.Price * 1.2) </span> @if (Model.Count > 5) { <ol> @foreach(var item in Model) { <li>@item.Name</li> } </ol> }
  • 19. Direnenciar código del server desde HTML ▪ Razor identifica el código del lado del servidor , buscando el símbolo @ . ▪ En sintaxis Razor , el símbolo @ tiene varios usos . Usted puede : ▪ Use @ para identificar el lado del servidor de C # código ▪ Use @@para rendir un símbolo @ en una página HTML . ▪ Utilice @ : declarar explícitamente una línea de texto como el contenido y no el código . ▪ Utilice < texto > para declarar explícitamente varias líneas de texto como el contenido y no el código . ▪ Para hacer que el texto sin codificación HTML , puede utilizar el helper Html.Raw ( ) .
  • 20. HTML Helpers ▪ Action Helpers ▪ Display Helpers ▪ The Begin Form Helper ▪ Editor Helpers ▪ Validation Helpers
  • 21. Action Helpers • Html.ActionLink() • Url.Action() @Html.ActionLink("Click here to view photo 1", "Display", new { id = 1 }) <a href="/photo/display/1"> Click here to view photo 1 </a> <img alt="This image came from an action" src="@Url.Action("GetImage", new { id = 1 })" /> <img alt="This image came from an action" src="/photo/getimage/1" })" />
  • 22. Display Helpers • Html.DisplayNameFor() • Html.DisplayFor() @Html.DisplayNameFor(model => model.CreatedDate) @Html.DisplayFor(model => model.CreatedDate) Created Date 03/12/2012
  • 23. The Begin Form Helper Html.BeginForm() @using (Html.BeginForm("Create", "Photo", FormMethod.Post, new { enctype = "multipart/form-data" })) { @* Place input controls here *@ } <form action="/Photo/Create" method="post“ enctype="multipart/form-data"> </form>
  • 24. Editor Helpers Html.LabelFor() Html.EditorFor() @Html.LabelFor(model => model.ContactMe) @Html.EditorFor(model => model.ContactMe) <label for="ContactMe"> Contact Me </label> <input type="checkbox" name="Description">
  • 25. Validation Helpers Html.ValidationSummary() Html.ValidationMessageFor() @Html.ValidationSummary() @Html.ValidationMessageFor(model => model.Email) <ul> <li>Please enter your last name</li> <li>Please enter a valid email address</li> </ul> Please enter a valid email address

Editor's Notes

  1. The action helpers described in this topic examine the routes defined in your web application to render the correct URLs. Students have not yet learned about the routing engine or how to modify routes. They will learn about routing in Module 7. Question: You want to render an HTML5 <audio> tag to play a sound file from an action. Would you use the Html.ActionLink() helper or the Url.Action() helper? Answer: You would use the Url.Action() helper because you are rendering an attribute within the <audio> tag, and not a complete <a> element.
  2. Question: You want to ensure that a view displays “This product was last changed on” before the ModifiedDate property. This text is declared in the class with the DisplayName annotation. What code would you write in the view? Answer: @Html.DisplayNameFor(model => model.ModifiedDate)
  3. Question: You have created a form with a file selector control that uses the GET method. You have set the enctype attribute to multipart/form-data but when you try to access the file in the action method, an exception is thrown. What have you possibly done incorrectly? Answer: You must use the POST method to upload files.
  4. Question: You have a property in the Product model class named ProductID. You want to include this in the HTML page so that client-side script can use the ProductID value. However, you do not want the value to be displayed to users. In the model class, you have annotated the ProductID property with the [HiddenInput(DisplayValue=false)] attribute. How will the Html.EditorFor() helper render this property? Answer: The Html.EditorFor() helper renders the following HTML: <input name="ProductID" type="hidden" value="id">
  5. Remind the students that they learned how to set validation requirements in model classes by using validation data annotations such as [Required] in Module 3. They have also learned how to check the validity of user data in a controller action by testing the ModelState.IsValid property in Module 4.