Portafolio de Diseño Gráfico por Giorgio B Huizinga
Modelo vista controlador
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. ../ 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. 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. ../ 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. {
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. <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
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. }
../ 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. // 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");
}