MVC
1. – Ejemplo: Hola Mundo
../Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System...
../ Views/Home/Index.aspx
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.View...
2. – Ejemplo: Acceso a datos
Agregamos la base de datos, en este caso cuelga del raiz pero podria colgar de Models si el
e...
../ Controllers/PersonasController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;...
{
try
{
// TODO: Add update logic here
db.Personas.Attach(persona);
db.ObjectStateManager.ChangeObjectState(persona,
Syste...
<br />
<%: Html.ActionLink("Crear Usuario", "Create") %>>
<br />
<%: Html.ActionLink("Ver todos los usuarios", "List") %>>...
../ Shared/Site.Master
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C/...
../ Controller/HomeControler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sy...
}
../ Controller/LibrosControler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
usin...
// GET: /Libros/Edit/5
public ActionResult Edit(int id)
{
Libro libro = (from lib in contexto.Libros
where lib.IdLibro == ...
catch
{
return View(libro);
}
}
}
}
Upcoming SlideShare
Loading in …5
×

Modelo vista controlador

688 views
518 views

Published on

Published in: Design, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
688
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
17
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Modelo vista controlador

  1. 1. MVC 1. – Ejemplo: Hola Mundo ../Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication1.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Puto examen"; return View(); } public ActionResult Index2() { Models.Usuario datos = new Models.Usuario(); datos.Nombre = "Juan"; datos.Ciudad = "Madrid"; datos.FechaAlta = new DateTime(2014, 04, 09); return View(datos); } [HttpPost] public ActionResult Index2(int edad) { ViewData["edad"] = edad; return View("VistaEdad"); } public ActionResult About() { return View(); } } }
  2. 2. ../ Views/Home/Index.aspx <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Página principal </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2><%: ViewData["Message"] %></h2> <p> Para obtener más información sobre ASP.NET MVC, visite el <a href="http://asp.net/mvc" title="sitio web de ASP.NET MVC">http://asp.net/mvc</a>. </p> </asp:Content> ../ Models/Usuario.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcApplication1.Models { public class Usuario { public string Nombre { get; set; } public string Ciudad { get; set; } public DateTime FechaAlta {get; set;} } } ../ Views/Home/Index2.aspx <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Usuario>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index2 </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Index2</h2> <%: Html.TextBoxFor(Model => Model.Nombre) %> <%: Html.TextBoxFor(Model => Model.Ciudad) %> <%: Html.TextBoxFor(Model => Model.FechaAlta) %> <br /> <h2>Introduce tu edad</h2> <form method="post" action="/Home/Index2"> <input type="text" name="edad" /> <input type="submit" /> </form> </asp:Content>
  3. 3. 2. – Ejemplo: Acceso a datos Agregamos la base de datos, en este caso cuelga del raiz pero podria colgar de Models si el enunciado asi lo pidiese. Este es el código subyacente. Modelo.edmx/ModeloDesigner.cs namespace MvcAccesoDatos { #region Contextos /// <summary> /// No hay documentación de metadatos disponible. /// </summary> public partial class DBPersonasEntities : ObjectContext { …………………………………………… Importantisimo llamar a la tabla en plural y al element en singular, como la clase. Se hace manual, visual studio no lo hace.
  4. 4. ../ Controllers/PersonasController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcAccesoDatos.Models; namespace MvcAccesoDatos.Controllers { public class PersonasController : Controller { // GET: /Personas/ private DBPersonasEntities db = new DBPersonasEntities(); public ActionResult Index() { return View(); } // GET: /Personas/List public ActionResult List() { return View(db.Personas.ToList()); } // GET: /Personas/Create public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Persona persona) { try { db.Personas.AddObject(persona); db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } public ActionResult Edit(int id) { Persona persona = db.Personas.Single(u => u.id == id); return View(persona); } // // POST: /Personas/Edit/5 [HttpPost] public ActionResult Edit(Persona persona)
  5. 5. { try { // TODO: Add update logic here db.Personas.Attach(persona); db.ObjectStateManager.ChangeObjectState(persona, System.Data.EntityState.Modified); db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } // // GET: /Personas/Delete/5 public ActionResult Delete(int id) { Persona persona = db.Personas.Single(u => u.id == id); return View(persona); } // // POST: /Personas/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { try { Persona persona = db.Personas.Single(u => u.id == id); db.Personas.DeleteObject(persona); db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } } } ../ Views/Personas/Index.aspx <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Base datos Repaso</title> </head> <body> <div> <h1> Base de datos repaso</h1>
  6. 6. <br /> <%: Html.ActionLink("Crear Usuario", "Create") %>> <br /> <%: Html.ActionLink("Ver todos los usuarios", "List") %>> </div> </body> </html> ../ Views/Personas/List.aspx Se genera automaticamente con nombre List, fuertemente tipada, clase de datos AccesoADatos.Persona Contenido del view: List ../ Views/Personas/Create.aspx Se general tal cual, similar a list. ../ Views/Personas/Edit.aspx Se general tal cual, similar a list. ../ Views/Personas/Delete.aspx Se general tal cual, similar a list. 3. – Ejemplo: Prueba final
  7. 7. ../ Shared/Site.Master <%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title> <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="page"> <div id="header"> <div id="title"> <h1>Librería</h1> </div> <div id="logindisplay"> <% Html.RenderPartial("LogOnUserControl"); %> </div> <div id="menucontainer"> <ul id="menu"> <li><%: Html.ActionLink("Página principal", "Index", "Home")%></li> <li><%: Html.ActionLink("Categorias", "Index", "Categorias")%></li> <li><%: Html.ActionLink("Libros", "Index", "Libros")%></li> <li><%: Html.ActionLink("Acerca de", "About", "Home")%></li> </ul> </div> </div> <div id="main"> <asp:ContentPlaceHolder ID="MainContent" runat="server" /> <div id="footer"> </div> </div> </div> </body> </html>
  8. 8. ../ Controller/HomeControler using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace LibreriaMVC.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Bienvenido a nuestra web"; return View(); } public ActionResult About() { return View(); } } } ../ Controller/CategoriasControler using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using LibreriaMVC.Models; namespace LibreriaMVC.Controllers { [Authorize] public class CategoriasController : Controller { static LibreriaMVCEntities contexto = new LibreriaMVCEntities(); // // GET: /Categorias/ public ActionResult Index() { return View(contexto.Categorias.ToList()); } public ActionResult LibrosDeCategoria(int id) { List<Libro> libros = (from lib in contexto.Libros where lib.IdCategoria == id select lib).ToList(); return View(libros); } }
  9. 9. } ../ Controller/LibrosControler using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using LibreriaMVC.Models; namespace LibreriaMVC.Controllers { [Authorize] public class LibrosController : Controller { LibreriaMVCEntities contexto = new LibreriaMVCEntities(); // // GET: /Libros/ public ActionResult Index() { return View(contexto.Libros.ToList()); } // // GET: /Libros/Create public ActionResult Create() { return View(); } // // POST: /Libros/Create [HttpPost] public ActionResult Create(Libro libro) { if (ModelState.IsValid) { try { contexto.Libros.AddObject(libro); contexto.SaveChanges(); return RedirectToAction("Index"); } catch { return View(libro); } } else return View(libro); } //
  10. 10. // GET: /Libros/Edit/5 public ActionResult Edit(int id) { Libro libro = (from lib in contexto.Libros where lib.IdLibro == id select lib).FirstOrDefault(); return View(libro); } // // POST: /Libros/Edit/5 [HttpPost] public ActionResult Edit(Libro libro) { if (ModelState.IsValid) { try { contexto.Libros.Attach(libro); contexto.ObjectStateManager.ChangeObjectState(libro, System.Data.EntityState.Modified); contexto.SaveChanges(); return RedirectToAction("Index"); } catch { return View(libro); } } return View(libro); } // // GET: /Libros/Delete/5 public ActionResult Delete(int id) { Libro libro = (from lib in contexto.Libros where lib.IdLibro == id select lib).FirstOrDefault(); return View(libro); } // // POST: /Libros/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirm(int id) { Libro libro = (from lib in contexto.Libros where lib.IdLibro == id select lib).FirstOrDefault(); try { contexto.Libros.DeleteObject(libro); contexto.SaveChanges(); return RedirectToAction("Index"); }
  11. 11. catch { return View(libro); } } } }

×