SlideShare una empresa de Scribd logo
1 de 11
Descargar para leer sin conexión
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();
}
}
}
../ 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>
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.
../ 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)
{
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>
<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
../ 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>
../ 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);
}
}
}
../ 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);
}
//
// 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");
}
catch
{
return View(libro);
}
}
}
}

Más contenido relacionado

La actualidad más candente

IT Camps Apps Office 365 Valencia 2014
IT Camps Apps Office 365 Valencia 2014IT Camps Apps Office 365 Valencia 2014
IT Camps Apps Office 365 Valencia 2014Adrian Diaz Cervera
 
Objetos implícitos
Objetos implícitosObjetos implícitos
Objetos implícitospaulacas
 
Taller desarrollando sitios web multiplataforma
Taller desarrollando sitios web multiplataformaTaller desarrollando sitios web multiplataforma
Taller desarrollando sitios web multiplataformaLuis Beltran
 
La magia de jquery
La magia de jqueryLa magia de jquery
La magia de jqueryAngelDX
 
Seguridad de aplicaciones web 2.0
Seguridad de aplicaciones web 2.0Seguridad de aplicaciones web 2.0
Seguridad de aplicaciones web 2.0Pablo Viquez
 
iDay Feb 2017 - Marcado de datos estructurados. Pónselo fácil a Google
iDay Feb 2017 - Marcado de datos estructurados. Pónselo fácil a GoogleiDay Feb 2017 - Marcado de datos estructurados. Pónselo fácil a Google
iDay Feb 2017 - Marcado de datos estructurados. Pónselo fácil a GoogleMiguel Ángel Pau
 
Servletacceso bd
Servletacceso bdServletacceso bd
Servletacceso bdmanuel
 
Primitive Obsession. FrontFest 2020
Primitive Obsession. FrontFest 2020Primitive Obsession. FrontFest 2020
Primitive Obsession. FrontFest 2020Aida Albarrán
 

La actualidad más candente (17)

IT Camps Apps Office 365 Valencia 2014
IT Camps Apps Office 365 Valencia 2014IT Camps Apps Office 365 Valencia 2014
IT Camps Apps Office 365 Valencia 2014
 
Objetos implícitos
Objetos implícitosObjetos implícitos
Objetos implícitos
 
Jquery parte 1
Jquery parte 1Jquery parte 1
Jquery parte 1
 
Taller desarrollando sitios web multiplataforma
Taller desarrollando sitios web multiplataformaTaller desarrollando sitios web multiplataforma
Taller desarrollando sitios web multiplataforma
 
(Muy breve) Introduccion a jQuery
(Muy breve) Introduccion a jQuery(Muy breve) Introduccion a jQuery
(Muy breve) Introduccion a jQuery
 
Android bootcamp 101 v2.0
Android bootcamp 101 v2.0Android bootcamp 101 v2.0
Android bootcamp 101 v2.0
 
Jquery
JqueryJquery
Jquery
 
JQuery-Tema 1
JQuery-Tema 1JQuery-Tema 1
JQuery-Tema 1
 
La magia de jquery
La magia de jqueryLa magia de jquery
La magia de jquery
 
Introduccion a Jquery
Introduccion a JqueryIntroduccion a Jquery
Introduccion a Jquery
 
04. Implementando APIs HTML5
04. Implementando APIs HTML5 04. Implementando APIs HTML5
04. Implementando APIs HTML5
 
Guia jQuery INCES Militar - Kurt Gude
Guia jQuery INCES Militar - Kurt GudeGuia jQuery INCES Militar - Kurt Gude
Guia jQuery INCES Militar - Kurt Gude
 
Seguridad de aplicaciones web 2.0
Seguridad de aplicaciones web 2.0Seguridad de aplicaciones web 2.0
Seguridad de aplicaciones web 2.0
 
Curso AngularJS - 5. rutas
Curso AngularJS - 5. rutasCurso AngularJS - 5. rutas
Curso AngularJS - 5. rutas
 
iDay Feb 2017 - Marcado de datos estructurados. Pónselo fácil a Google
iDay Feb 2017 - Marcado de datos estructurados. Pónselo fácil a GoogleiDay Feb 2017 - Marcado de datos estructurados. Pónselo fácil a Google
iDay Feb 2017 - Marcado de datos estructurados. Pónselo fácil a Google
 
Servletacceso bd
Servletacceso bdServletacceso bd
Servletacceso bd
 
Primitive Obsession. FrontFest 2020
Primitive Obsession. FrontFest 2020Primitive Obsession. FrontFest 2020
Primitive Obsession. FrontFest 2020
 

Similar a Modelo vista controlador

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 MVCDanae Aguilar Guzmán
 
Seminario jquery, html5 y wicket
Seminario jquery, html5 y wicketSeminario jquery, html5 y wicket
Seminario jquery, html5 y wicketAdrià Solé Orrit
 
Parte II. Notas Rapidas (sticky notes) App W8: MVVM y SQLite.
Parte II. Notas Rapidas (sticky notes) App W8: MVVM y SQLite.Parte II. Notas Rapidas (sticky notes) App W8: MVVM y SQLite.
Parte II. Notas Rapidas (sticky notes) App W8: MVVM y SQLite.Juan Manuel
 
Introducción al desarrollo Web: Frontend con Angular 6
Introducción al desarrollo Web: Frontend con Angular 6Introducción al desarrollo Web: Frontend con Angular 6
Introducción al desarrollo Web: Frontend con Angular 6Gabriela Bosetti
 
Prueba De Aplicaciones Web con Selenium 2 y WebDriver
Prueba De Aplicaciones Web con Selenium 2 y WebDriverPrueba De Aplicaciones Web con Selenium 2 y WebDriver
Prueba De Aplicaciones Web con Selenium 2 y WebDriverDavid Gómez García
 
Introducción a AngularJS
Introducción a AngularJS Introducción a AngularJS
Introducción a AngularJS Marcos Reynoso
 
Reconnect(); Sevilla - Universal Windows Platform
Reconnect(); Sevilla - Universal Windows PlatformReconnect(); Sevilla - Universal Windows Platform
Reconnect(); Sevilla - Universal Windows PlatformJavier Suárez Ruiz
 
LabAndroid: Taller "Mi Primera Aplicación Android"
LabAndroid: Taller "Mi Primera Aplicación Android"LabAndroid: Taller "Mi Primera Aplicación Android"
LabAndroid: Taller "Mi Primera Aplicación Android"Alberto Ruibal
 
Guía Practica conexión BD 2021
Guía Practica conexión BD  2021Guía Practica conexión BD  2021
Guía Practica conexión BD 2021lissette_torrealba
 
DocumentacióN Del Sitio Web En Xml
DocumentacióN Del Sitio Web En XmlDocumentacióN Del Sitio Web En Xml
DocumentacióN Del Sitio Web En XmlAntonio
 
DocumentacióN Del Sitio Web En Xml
DocumentacióN Del Sitio Web En XmlDocumentacióN Del Sitio Web En Xml
DocumentacióN Del Sitio Web En XmlAntonio
 

Similar a Modelo vista controlador (20)

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
 
Seminario jquery, html5 y wicket
Seminario jquery, html5 y wicketSeminario jquery, html5 y wicket
Seminario jquery, html5 y wicket
 
Parte II. Notas Rapidas (sticky notes) App W8: MVVM y SQLite.
Parte II. Notas Rapidas (sticky notes) App W8: MVVM y SQLite.Parte II. Notas Rapidas (sticky notes) App W8: MVVM y SQLite.
Parte II. Notas Rapidas (sticky notes) App W8: MVVM y SQLite.
 
MODELO VISTA CONTROLADOR EN PHP
MODELO VISTA CONTROLADOR EN PHPMODELO VISTA CONTROLADOR EN PHP
MODELO VISTA CONTROLADOR EN PHP
 
Ajax
AjaxAjax
Ajax
 
Introducción al desarrollo Web: Frontend con Angular 6
Introducción al desarrollo Web: Frontend con Angular 6Introducción al desarrollo Web: Frontend con Angular 6
Introducción al desarrollo Web: Frontend con Angular 6
 
Phonegap
PhonegapPhonegap
Phonegap
 
Prueba De Aplicaciones Web con Selenium 2 y WebDriver
Prueba De Aplicaciones Web con Selenium 2 y WebDriverPrueba De Aplicaciones Web con Selenium 2 y WebDriver
Prueba De Aplicaciones Web con Selenium 2 y WebDriver
 
Jquery para principianes
Jquery para principianesJquery para principianes
Jquery para principianes
 
J M E R L I N P H P
J M E R L I N P H PJ M E R L I N P H P
J M E R L I N P H P
 
Introducción a AngularJS
Introducción a AngularJS Introducción a AngularJS
Introducción a AngularJS
 
Mi app-asp-net-mvc2
Mi app-asp-net-mvc2Mi app-asp-net-mvc2
Mi app-asp-net-mvc2
 
APIREST LARAVEL Y PHP.pptx
APIREST LARAVEL Y PHP.pptxAPIREST LARAVEL Y PHP.pptx
APIREST LARAVEL Y PHP.pptx
 
Reconnect(); Sevilla - Universal Windows Platform
Reconnect(); Sevilla - Universal Windows PlatformReconnect(); Sevilla - Universal Windows Platform
Reconnect(); Sevilla - Universal Windows Platform
 
LabAndroid: Taller "Mi Primera Aplicación Android"
LabAndroid: Taller "Mi Primera Aplicación Android"LabAndroid: Taller "Mi Primera Aplicación Android"
LabAndroid: Taller "Mi Primera Aplicación Android"
 
Manual Basico De Struts
Manual Basico De StrutsManual Basico De Struts
Manual Basico De Struts
 
Guía Practica conexión BD 2021
Guía Practica conexión BD  2021Guía Practica conexión BD  2021
Guía Practica conexión BD 2021
 
Introduccion mvc
Introduccion mvcIntroduccion mvc
Introduccion mvc
 
DocumentacióN Del Sitio Web En Xml
DocumentacióN Del Sitio Web En XmlDocumentacióN Del Sitio Web En Xml
DocumentacióN Del Sitio Web En Xml
 
DocumentacióN Del Sitio Web En Xml
DocumentacióN Del Sitio Web En XmlDocumentacióN Del Sitio Web En Xml
DocumentacióN Del Sitio Web En Xml
 

Último

Jesus Diaz afiche Manierismo .pdf arquitectura
Jesus Diaz afiche Manierismo .pdf arquitecturaJesus Diaz afiche Manierismo .pdf arquitectura
Jesus Diaz afiche Manierismo .pdf arquitecturajesusgrosales12
 
Arquitectura moderna / Nazareth Bermúdez
Arquitectura moderna / Nazareth BermúdezArquitectura moderna / Nazareth Bermúdez
Arquitectura moderna / Nazareth BermúdezNaza59
 
CERTIFICACIÓN DE CAPACITACIÓN PARA EL CENSO - tfdxwBRz6f3AP7QU.pdf
CERTIFICACIÓN DE CAPACITACIÓN PARA EL CENSO - tfdxwBRz6f3AP7QU.pdfCERTIFICACIÓN DE CAPACITACIÓN PARA EL CENSO - tfdxwBRz6f3AP7QU.pdf
CERTIFICACIÓN DE CAPACITACIÓN PARA EL CENSO - tfdxwBRz6f3AP7QU.pdfasnsdt
 
Arquitectura moderna nazareth bermudez PSM
Arquitectura moderna nazareth bermudez PSMArquitectura moderna nazareth bermudez PSM
Arquitectura moderna nazareth bermudez PSMNaza59
 
TIPOS DE LINEAS utilizados en dibujo técnico mecánico
TIPOS DE LINEAS utilizados en dibujo técnico mecánicoTIPOS DE LINEAS utilizados en dibujo técnico mecánico
TIPOS DE LINEAS utilizados en dibujo técnico mecánicoWilsonChambi4
 
TRABAJO DESDE CASA REGION INSULAR.docx.pdf
TRABAJO DESDE CASA REGION INSULAR.docx.pdfTRABAJO DESDE CASA REGION INSULAR.docx.pdf
TRABAJO DESDE CASA REGION INSULAR.docx.pdfDamarysNavarro1
 
PDU - PLAN DE DESARROLLO URBANO DE LA CIUDAD DE CHICLAYO
PDU - PLAN DE DESARROLLO URBANO DE LA CIUDAD DE CHICLAYOPDU - PLAN DE DESARROLLO URBANO DE LA CIUDAD DE CHICLAYO
PDU - PLAN DE DESARROLLO URBANO DE LA CIUDAD DE CHICLAYOManuelBustamante49
 
plantilla-de-messi-1.pdf es muy especial
plantilla-de-messi-1.pdf es muy especialplantilla-de-messi-1.pdf es muy especial
plantilla-de-messi-1.pdf es muy especialAndreaMlaga1
 
428483625-ANALISIS-DEL-REGLAMENTO-DE-METRADOS.pptx
428483625-ANALISIS-DEL-REGLAMENTO-DE-METRADOS.pptx428483625-ANALISIS-DEL-REGLAMENTO-DE-METRADOS.pptx
428483625-ANALISIS-DEL-REGLAMENTO-DE-METRADOS.pptxReneSalas18
 
PRESENTACION SOBRE EL PROYECTO DE GRADO .
PRESENTACION SOBRE EL PROYECTO DE GRADO .PRESENTACION SOBRE EL PROYECTO DE GRADO .
PRESENTACION SOBRE EL PROYECTO DE GRADO .Rosa329296
 
Maquetas-modelos-prototipos-Mapa mental-.pdf
Maquetas-modelos-prototipos-Mapa mental-.pdfMaquetas-modelos-prototipos-Mapa mental-.pdf
Maquetas-modelos-prototipos-Mapa mental-.pdforianaandrade11
 
APORTES Y CARACTERISTICAS DE LAS OBRAS DE CORBUSIER. MIES VAN DER ROHE
APORTES Y CARACTERISTICAS DE LAS OBRAS DE  CORBUSIER. MIES VAN DER ROHEAPORTES Y CARACTERISTICAS DE LAS OBRAS DE  CORBUSIER. MIES VAN DER ROHE
APORTES Y CARACTERISTICAS DE LAS OBRAS DE CORBUSIER. MIES VAN DER ROHEgonzalezdfidelibus
 
SENSICO CURSO DE EXPEDIENTE TECNICO DE OBRAS
SENSICO CURSO DE EXPEDIENTE TECNICO DE OBRASSENSICO CURSO DE EXPEDIENTE TECNICO DE OBRAS
SENSICO CURSO DE EXPEDIENTE TECNICO DE OBRASpaotavo97
 
EL CONCEPTO Y EL PARTIDO ARQUITECTONICO.pdf
EL CONCEPTO Y EL PARTIDO ARQUITECTONICO.pdfEL CONCEPTO Y EL PARTIDO ARQUITECTONICO.pdf
EL CONCEPTO Y EL PARTIDO ARQUITECTONICO.pdfCeciliaTernR1
 
Brochure Tuna Haus _ Hecho para mascotas.pdf
Brochure Tuna Haus _ Hecho para mascotas.pdfBrochure Tuna Haus _ Hecho para mascotas.pdf
Brochure Tuna Haus _ Hecho para mascotas.pdfhellotunahaus
 
Quinto-Cuaderno-del-Alumno-optimizado.pdf
Quinto-Cuaderno-del-Alumno-optimizado.pdfQuinto-Cuaderno-del-Alumno-optimizado.pdf
Quinto-Cuaderno-del-Alumno-optimizado.pdfPapiElMejor1
 
Le Corbusier y Mies van der Rohe: Aportes a la Arquitectura Moderna
Le Corbusier y Mies van der Rohe: Aportes a la Arquitectura ModernaLe Corbusier y Mies van der Rohe: Aportes a la Arquitectura Moderna
Le Corbusier y Mies van der Rohe: Aportes a la Arquitectura Modernasofpaolpz
 
Presentacion de 100 psicologos dijeron.pptx
Presentacion de 100 psicologos dijeron.pptxPresentacion de 100 psicologos dijeron.pptx
Presentacion de 100 psicologos dijeron.pptxbarbaracantuflr
 
2024-EL CAMBIO CLIMATICO Y SUS EFECTOS EN EL PERÚ Y EL MUNDO.pdf
2024-EL CAMBIO CLIMATICO Y SUS EFECTOS EN EL PERÚ Y EL MUNDO.pdf2024-EL CAMBIO CLIMATICO Y SUS EFECTOS EN EL PERÚ Y EL MUNDO.pdf
2024-EL CAMBIO CLIMATICO Y SUS EFECTOS EN EL PERÚ Y EL MUNDO.pdfcnaomi195
 
Portafolio de Diseño Gráfico por Giorgio B Huizinga
Portafolio de Diseño Gráfico por Giorgio B HuizingaPortafolio de Diseño Gráfico por Giorgio B Huizinga
Portafolio de Diseño Gráfico por Giorgio B Huizingagbhuizinga2000
 

Último (20)

Jesus Diaz afiche Manierismo .pdf arquitectura
Jesus Diaz afiche Manierismo .pdf arquitecturaJesus Diaz afiche Manierismo .pdf arquitectura
Jesus Diaz afiche Manierismo .pdf arquitectura
 
Arquitectura moderna / Nazareth Bermúdez
Arquitectura moderna / Nazareth BermúdezArquitectura moderna / Nazareth Bermúdez
Arquitectura moderna / Nazareth Bermúdez
 
CERTIFICACIÓN DE CAPACITACIÓN PARA EL CENSO - tfdxwBRz6f3AP7QU.pdf
CERTIFICACIÓN DE CAPACITACIÓN PARA EL CENSO - tfdxwBRz6f3AP7QU.pdfCERTIFICACIÓN DE CAPACITACIÓN PARA EL CENSO - tfdxwBRz6f3AP7QU.pdf
CERTIFICACIÓN DE CAPACITACIÓN PARA EL CENSO - tfdxwBRz6f3AP7QU.pdf
 
Arquitectura moderna nazareth bermudez PSM
Arquitectura moderna nazareth bermudez PSMArquitectura moderna nazareth bermudez PSM
Arquitectura moderna nazareth bermudez PSM
 
TIPOS DE LINEAS utilizados en dibujo técnico mecánico
TIPOS DE LINEAS utilizados en dibujo técnico mecánicoTIPOS DE LINEAS utilizados en dibujo técnico mecánico
TIPOS DE LINEAS utilizados en dibujo técnico mecánico
 
TRABAJO DESDE CASA REGION INSULAR.docx.pdf
TRABAJO DESDE CASA REGION INSULAR.docx.pdfTRABAJO DESDE CASA REGION INSULAR.docx.pdf
TRABAJO DESDE CASA REGION INSULAR.docx.pdf
 
PDU - PLAN DE DESARROLLO URBANO DE LA CIUDAD DE CHICLAYO
PDU - PLAN DE DESARROLLO URBANO DE LA CIUDAD DE CHICLAYOPDU - PLAN DE DESARROLLO URBANO DE LA CIUDAD DE CHICLAYO
PDU - PLAN DE DESARROLLO URBANO DE LA CIUDAD DE CHICLAYO
 
plantilla-de-messi-1.pdf es muy especial
plantilla-de-messi-1.pdf es muy especialplantilla-de-messi-1.pdf es muy especial
plantilla-de-messi-1.pdf es muy especial
 
428483625-ANALISIS-DEL-REGLAMENTO-DE-METRADOS.pptx
428483625-ANALISIS-DEL-REGLAMENTO-DE-METRADOS.pptx428483625-ANALISIS-DEL-REGLAMENTO-DE-METRADOS.pptx
428483625-ANALISIS-DEL-REGLAMENTO-DE-METRADOS.pptx
 
PRESENTACION SOBRE EL PROYECTO DE GRADO .
PRESENTACION SOBRE EL PROYECTO DE GRADO .PRESENTACION SOBRE EL PROYECTO DE GRADO .
PRESENTACION SOBRE EL PROYECTO DE GRADO .
 
Maquetas-modelos-prototipos-Mapa mental-.pdf
Maquetas-modelos-prototipos-Mapa mental-.pdfMaquetas-modelos-prototipos-Mapa mental-.pdf
Maquetas-modelos-prototipos-Mapa mental-.pdf
 
APORTES Y CARACTERISTICAS DE LAS OBRAS DE CORBUSIER. MIES VAN DER ROHE
APORTES Y CARACTERISTICAS DE LAS OBRAS DE  CORBUSIER. MIES VAN DER ROHEAPORTES Y CARACTERISTICAS DE LAS OBRAS DE  CORBUSIER. MIES VAN DER ROHE
APORTES Y CARACTERISTICAS DE LAS OBRAS DE CORBUSIER. MIES VAN DER ROHE
 
SENSICO CURSO DE EXPEDIENTE TECNICO DE OBRAS
SENSICO CURSO DE EXPEDIENTE TECNICO DE OBRASSENSICO CURSO DE EXPEDIENTE TECNICO DE OBRAS
SENSICO CURSO DE EXPEDIENTE TECNICO DE OBRAS
 
EL CONCEPTO Y EL PARTIDO ARQUITECTONICO.pdf
EL CONCEPTO Y EL PARTIDO ARQUITECTONICO.pdfEL CONCEPTO Y EL PARTIDO ARQUITECTONICO.pdf
EL CONCEPTO Y EL PARTIDO ARQUITECTONICO.pdf
 
Brochure Tuna Haus _ Hecho para mascotas.pdf
Brochure Tuna Haus _ Hecho para mascotas.pdfBrochure Tuna Haus _ Hecho para mascotas.pdf
Brochure Tuna Haus _ Hecho para mascotas.pdf
 
Quinto-Cuaderno-del-Alumno-optimizado.pdf
Quinto-Cuaderno-del-Alumno-optimizado.pdfQuinto-Cuaderno-del-Alumno-optimizado.pdf
Quinto-Cuaderno-del-Alumno-optimizado.pdf
 
Le Corbusier y Mies van der Rohe: Aportes a la Arquitectura Moderna
Le Corbusier y Mies van der Rohe: Aportes a la Arquitectura ModernaLe Corbusier y Mies van der Rohe: Aportes a la Arquitectura Moderna
Le Corbusier y Mies van der Rohe: Aportes a la Arquitectura Moderna
 
Presentacion de 100 psicologos dijeron.pptx
Presentacion de 100 psicologos dijeron.pptxPresentacion de 100 psicologos dijeron.pptx
Presentacion de 100 psicologos dijeron.pptx
 
2024-EL CAMBIO CLIMATICO Y SUS EFECTOS EN EL PERÚ Y EL MUNDO.pdf
2024-EL CAMBIO CLIMATICO Y SUS EFECTOS EN EL PERÚ Y EL MUNDO.pdf2024-EL CAMBIO CLIMATICO Y SUS EFECTOS EN EL PERÚ Y EL MUNDO.pdf
2024-EL CAMBIO CLIMATICO Y SUS EFECTOS EN EL PERÚ Y EL MUNDO.pdf
 
Portafolio de Diseño Gráfico por Giorgio B Huizinga
Portafolio de Diseño Gráfico por Giorgio B HuizingaPortafolio de Diseño Gráfico por Giorgio B Huizinga
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
  • 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. ../ 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"); }