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).
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>
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.
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)
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.
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">
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.