Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Pgina 1
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
e. Controlador
Es la capa que sirve de enlace entre la vista y el modelo. Enva comandos al
modelo para actualizar su estado, y a la vista correspondiente para cambiar
su presentacin, pero no es el encargado de manipular los datos ni de
generar una salida.
Para comprender un poco ms este patrn de diseo veamos cmo funciona
en una aplicacin web comn:
Pgina 2
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
f.
Ventajas de MVC
Reutilizar Cdigo
Cualquier Framework que creado a partir de MVC te permite reutilizar
cdigo, regresar vistas totales o parciales, evitando duplicar estilos o
contenido en las vistas. Todo el manejo de datos se realiza en los
modelos, por lo que si modificas tu base de datos solo es necesario
modificar el modelo correspondiente para que permita manejar los
datos actualizados, sin necesidad de actualizar cada lugar donde es
utilizado.
g. Conclusiones
MVC es un patrn de diseo enfocado a separar las responsabilidades dentro
de nuestra aplicacin y es muy utilizado en la web por su enfoque y las
ventajas que ofrece con respecto a algunas otras formas o patrones de
desarrollo de aplicaciones web. Recordemos que aunque los patrones de
diseo son muy tiles en el desarrollo de software, no siempre es necesario
usarlos y eso no significa que la aplicacin est mal diseada, algunas
veces no son necesarios y mucho menos obligatorios, a veces abusar de los
patrones de diseo puede traer ms problemas de los que resuelve.
Pgina 3
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
DESARROLLO
1. Iniciamos el Sistema Operativo Windows.
Pgina 4
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 5
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
3.- Seleccionamos la ficha web y escoges Aplicacin Web ASP. Net, por ultimo clic en
aceptar.
Pgina 6
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 7
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 8
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 9
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 10
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
13.- Ahora una vez una llenado los atributos vamos a proceder especificar que
nuestro cdigo_estudiante sea autoincrementado para eso seleccionamos el atributo
y luego nos dirigimos a la propiedad Identity Specification
Pgina 11
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 12
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 13
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 14
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
21.- Ahora procederemos a crear nuestro modelo de datos desde visual Studio 2013
22.- escogemos la Ficha datos y escogemos ADO NET Entity Data Model
Pgina 15
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 16
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
25.- Clic en nueva conexin para poder crear nuestra cadena de conexin a nuestra
base de datos.
Pgina 17
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
27.- como vemos nuestra conexin fue exitosa as que aceptamos y luego clic en
aceptar.
Pgina 18
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 19
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
32.- ahora presionamos CTRL + Mayus + S para guardar todo el proyecto .Luego
procederemos a crear nuestro controlador
Pgina 20
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 21
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
35.- nos motrara el controlador con todas las acciones de Editar Eliminar
Listar y Crear ya implementadas
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.Mvc;
namespace DEMO_MVC5.Controllers
{
public class EstudianteController : Controller
{
// GET: Estudiante
public ActionResult Index()
{
return View();
}
// GET: Estudiante/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Estudiante/Create
public ActionResult Create()
{
return View();
}
Pgina 22
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
// POST: Estudiante/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Estudiante/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Estudiante/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Estudiante/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Estudiante/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Pgina 23
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
}
}
37.- Ahora procederemos a crear nuestra Vista para esto hacemos siguiente clic
derecho en ndex y escoger agregar vista
Pgina 24
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
38.- Ahora al tipo de plantilla escogemos List ya que le diremos que al momento que
carga el archivo ndex me muestre todos los estudiantes que tiene mi Base de Datos.
En clase modelo escogemos a la tabla estudiante que ha sido mapeada en mi vista
modelo.
Pgina 25
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
40.- como vern ya nos muestra con todos los atributos del estudiante nuestra vista
hecha con razor.
Pgina 26
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
<td>
@Html.DisplayFor(modelItem => item.Codigo_Estudiante)
</td>
<td>
@Html.DisplayFor(modelItem => item.Nombre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Apellido_Paterno)
</td>
<td>
@Html.DisplayFor(modelItem => item.Apellido_Materno)
</td>
<td>
@Html.DisplayFor(modelItem => item.Estado)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
Pgina 27
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
43.- Ahora procederemos a pasarle datos a la vista. Para eso trabajaremos con la
vista controlador en el archivo EstudianteController.cs
Primero hacemos referencia a nuestra vista modelo
using DEMO_MVC5.Models;
Segundo creamos una variable que obtendr acceso a toda nuestra base de
datos
UniversidadEntities Datos = new UniversidadEntities();
Tercero modificamos la accin del index creando una variable la cual tendr acceso
a todos los datos de la tabla estudiante:
public ActionResult Index()
{
var DatosEstudiante = Datos.Estudiante;
return View(DatosEstudiante);
}
Pgina 28
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
// GET: Estudiante/Create
public ActionResult Create()
{
return View();
}
// POST: Estudiante/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Estudiante/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Estudiante/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Estudiante/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Estudiante/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
Pgina 29
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
}
catch
{
return View();
}
}
}
}
46.- Hasta Esta Oportunidad Tenemos Listo el Listado de Todos los estudiantes.
Ahora procederemos a hacer el registro de nuevos estudiantes.
Para eso trabajaremos en la vista controlador en el archivo EstudianteController.cs
Y buscamos la accin Create y le damos clic derecho agregar vista.
Pgina 30
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 31
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 32
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Estudiante</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Codigo_Estudiante, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Codigo_Estudiante, new { htmlAttributes
= new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Codigo_Estudiante, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Nombre, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Nombre, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Nombre, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Paterno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Paterno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Paterno, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Materno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Materno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Materno, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Estado, htmlAttributes: new { @class =
"control-label col-md-2" })
Pgina 33
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
<div class="col-md-10">
@Html.EditorFor(model => model.Estado, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Estado, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Pgina 34
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 35
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
52.- Ahora procederemos a personalizar la vista Create por que el cdigo del
estudiante es autogenerado por lo cual no deberamos de ingresar entonces lo
borramos del cdigo fuente y el archivo quedara de esta manera:
Codigo fuente archivo crate.cshtml
@model DEMO_MVC5.Models.Estudiante
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Registro de Estudiantes</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Nombre, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Nombre, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Nombre, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Paterno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Paterno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Paterno, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Materno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Materno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Materno, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Estado, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Estado, new { htmlAttributes = new {
@class = "form-control" } })
Pgina 36
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 37
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
// POST: Estudiante/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{ //Creamos una variable del tipo estudiante
Estudiante estudiantes = new Estudiante();
// ahora le pasamos los datos ingresados por teclado a cada atributo
estudiantes.Nombre =collection["Nombre"];
estudiantes.Apellido_Paterno = collection["Apellido_Paterno"];
estudiantes.Apellido_Materno = collection["Apellido_Materno"];
// como el tipo de dato del estado es byte por eso lo convertimos
estudiantes.Estado = Convert.ToByte(collection["Estado"]);
//Ahora Agregamos a la entidad
Datos.Estudiante.Add(estudiantes);
// hacemos el guardado
Datos.SaveChanges();
//redireccionamos a la pagina index
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Pgina 38
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 39
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
en
el
la
accin
GET
en
el
mismo
achivo
Pgina 40
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
60.- Ahora como plantilla escogemos EDIT luego seleccionamos la clase modelo
estudiante Activamos el check - y agregar
Pgina 41
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
@model DEMO_MVC5.Models.Estudiante
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Estudiante</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Codigo_Estudiante, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Codigo_Estudiante, new { htmlAttributes
= new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Codigo_Estudiante, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Nombre, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Nombre, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Nombre, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Paterno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Paterno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Paterno, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Materno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Materno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Materno, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
Pgina 42
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 43
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
63.- Antes de ejecutar y probar el archivo debemos de modificar unas lnea de cdigo
en el archivo index.cshtml casi en las ultimas lneas encontraremos esto
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Codigo_Estudiante }) |
@Html.ActionLink("Details", "Details", new { id=item.Codigo_Estudiante }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Codigo_Estudiante })
</td>
64.- Ahora si probaremos el archivo edit.cshtml. Para comprobar que todo vaya
correctamente
Y le damos clic en Edit.
Pgina 44
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
65.- y Ahora Veremos que efectivamente nos muestra la vista Editar. Por qu nos
trajo los datos del registro seleccionado listo para poder actualizar sus datos
66. Ahora pasaremos a programar la accin para poder actualizar los datos y para
eso nos posicionamos en GET donde haremos una consulta LIN Q
// GET: Estudiante/Edit/5
public ActionResult Edit(int id)
{
var dataestudiante = (from e in Datos.Estudiante where id ==
e.Codigo_Estudiante select e).First();
return View(dataestudiante);
}
Pgina 45
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.Mvc;
DEMO_MVC5.Models;
namespace DEMO_MVC5.Controllers
{
public class EstudianteController : Controller
{
UniversidadEntities Datos = new UniversidadEntities();
// GET: Estudiante
public ActionResult Index()
{
var DatosEstudiante = Datos.Estudiante;
return View(DatosEstudiante);
}
// GET: Estudiante/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Estudiante/Create
public ActionResult Create()
{
return View();
}
// POST: Estudiante/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
Pgina 46
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 47
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
69.- Ahora ejecutamos el proyecto para ver que todo corra bien:
Para probar haremos clic en Edit.
Pgina 48
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 49
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
72.- Ahora solo nos queda Trabajar la vista Eliminar para eso nos posicionamos en
la accin Get de eliminar clic derecho agregar vista.
Pgina 50
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 51
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
76.- Una vez creada la vista procedemos a agregar cdigo a la accin delete en el
archivo EstudianteController.cs
// GET: Estudiante/Delete/5
public ActionResult Delete(int id)
{ // Realizamos la consulta LINQ
var dataestudiante = (from e in Datos.Estudiante where id ==
e.Codigo_Estudiante select e).First();
return View(dataestudiante);
}
77.- Ahora Tambin nos vamos a la accin eliminar pero de POST y ingresamos el
siguiente cdigo.
// POST: Estudiante/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
Pgina 52
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 53
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
79.- Nos mostrara esta vista de confirmacin de eliminar. Y hacemos clic en eliminar
Pgina 54
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
81.- Ahora trabajaremos la vista details para eso nos ubicamos en la accin
details y clic derecho agregar vista
Pgina 55
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
84.- Ahora editaremos la ltima lnea de esta vista para poder utilizarla
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.PrimaryKey */ }) |
@Html.ActionLink("Back to List", "Index")
</p>
Pgina 56
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Codigo_Estudiante)
</dt>
<dd>
@Html.DisplayFor(model => model.Codigo_Estudiante)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Nombre)
</dt>
<dd>
@Html.DisplayFor(model => model.Nombre)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Apellido_Paterno)
</dt>
<dd>
@Html.DisplayFor(model => model.Apellido_Paterno)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Apellido_Materno)
</dt>
<dd>
@Html.DisplayFor(model => model.Apellido_Materno)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Estado)
</dt>
<dd>
@Html.DisplayFor(model => model.Estado)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.Codigo_Estudiante }) |
@Html.ActionLink("Back to List", "Index")
</p>
// GET: Estudiante/Details/5
public ActionResult Details(int id)
{
var dataestudiante = (from e in Datos.Estudiante where id ==
e.Codigo_Estudiante select e).First();
Pgina 57
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
return View(dataestudiante);
}
Pgina 58
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Pgina 59
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
89.- Entonces teniendo ya todo el CRUD completo vamos a hacer unos pequeos
ajustes a las vistas empezaremos por:
Vista Create:
Codigo fuente Archivo crate.cshtml
@model DEMO_MVC5.Models.Estudiante
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Registro de Estudiantes</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Nombre, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Nombre, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Nombre, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Paterno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Paterno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Paterno, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Materno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Materno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Materno, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Estado, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Estado, new { htmlAttributes = new {
@class = "form-control" } })
Pgina 60
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Vista Editar:
Cdigo fuente Archivo edit.cshtml
@model DEMO_MVC5.Models.Estudiante
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Editar Estudiante</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Nombre, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Nombre, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Nombre, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Paterno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Paterno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Paterno, "", new {
@class = "text-danger" })
</div>
</div>
Pgina 61
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
<div class="form-group">
@Html.LabelFor(model => model.Apellido_Materno, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Apellido_Materno, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Apellido_Materno, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Estado, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Estado, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Estado, "", new { @class =
"text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Guardar" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Regresar a Inicio", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Pgina 62
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Vista Delete:
Cdigo Fuente delete.cshtml
@model DEMO_MVC5.Models.Estudiante
<h3>esta seguro de Eliminar ?</h3>
<div>
<h4>Eliminar Estudiante</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Codigo_Estudiante)
</dt>
<dd>
@Html.DisplayFor(model => model.Codigo_Estudiante)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Nombre)
</dt>
<dd>
@Html.DisplayFor(model => model.Nombre)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Apellido_Paterno)
</dt>
<dd>
@Html.DisplayFor(model => model.Apellido_Paterno)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Apellido_Materno)
</dt>
<dd>
@Html.DisplayFor(model => model.Apellido_Materno)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Estado)
</dt>
<dd>
@Html.DisplayFor(model => model.Estado)
</dd>
</dl>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Eliminar" class="btn btn-default" /> |
@Html.ActionLink("Regresar a Inicio", "Index")
Pgina 63
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
</div>
}
</div>
Vista Detalis:
Codigo fuente archivo details.cshtml
@model DEMO_MVC5.Models.Estudiante
<div>
<h4>Estudiante</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Codigo_Estudiante)
</dt>
<dd>
@Html.DisplayFor(model => model.Codigo_Estudiante)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Nombre)
</dt>
<dd>
@Html.DisplayFor(model => model.Nombre)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Apellido_Paterno)
</dt>
<dd>
@Html.DisplayFor(model => model.Apellido_Paterno)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Apellido_Materno)
</dt>
<dd>
@Html.DisplayFor(model => model.Apellido_Materno)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Estado)
</dt>
<dd>
@Html.DisplayFor(model => model.Estado)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Editar", "Edit", new { id = Model.Codigo_Estudiante }) |
Pgina 64
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Vista ndex:
Pgina 65
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
</td>
</tr>
}
</table>
Una vez hecho las modificaciones tambin colocaremos el cdigo fuente del
archivo EstudianteControllers.cs
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.Mvc;
DEMO_MVC5.Models;
namespace DEMO_MVC5.Controllers
{
public class EstudianteController : Controller
{
UniversidadEntities Datos = new UniversidadEntities();
// GET: Estudiante
public ActionResult Index()
{
var DatosEstudiante = Datos.Estudiante;
return View(DatosEstudiante);
}
// GET: Estudiante/Details/5
public ActionResult Details(int id)
{
var dataestudiante = (from e in Datos.Estudiante where id ==
e.Codigo_Estudiante select e).First();
return View(dataestudiante);
}
// GET: Estudiante/Create
public ActionResult Create()
{
return View();
}
// POST: Estudiante/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{ //Creamos una variable del tipo estudiante
Estudiante estudiantes = new Estudiante();
// ahora le pasamos los datos ingresados por teclado a cada atributo
Pgina 66
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
estudiantes.Nombre =collection["Nombre"];
estudiantes.Apellido_Paterno = collection["Apellido_Paterno"];
estudiantes.Apellido_Materno = collection["Apellido_Materno"];
// como el tipo de dato del estado es byte por eso lo convertimos
estudiantes.Estado = Convert.ToByte(collection["Estado"]);
//Ahora Agregamos a la entidad
Datos.Estudiante.Add(estudiantes);
// hacemos el guardado
Datos.SaveChanges();
//redireccionamos a la pagina index
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Estudiante/Edit/5
public ActionResult Edit(int id)
{
var dataestudiante = (from e in Datos.Estudiante where id ==
e.Codigo_Estudiante select e).First();
return View(dataestudiante);
}
// POST: Estudiante/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
var dataestudiante = (from e in Datos.Estudiante where id ==
e.Codigo_Estudiante select e).First();
// ahora le pasamos los datos ingresados por teclado a cada atributo
dataestudiante.Nombre = collection["Nombre"];
dataestudiante.Apellido_Paterno = collection["Apellido_Paterno"];
dataestudiante.Apellido_Materno = collection["Apellido_Materno"];
// como el tipo de dato del estado es byte por eso lo convertimos
dataestudiante.Estado = Convert.ToByte(collection["Estado"]);
// hacemos el guardado
Datos.SaveChanges();
//redireccionamos a la pagina index
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Estudiante/Delete/5
public ActionResult Delete(int id)
{ // Realizamos la consulta LINQ
var dataestudiante = (from e in Datos.Estudiante where id ==
e.Codigo_Estudiante select e).First();
return View(dataestudiante);
}
// POST: Estudiante/Delete/5
Pgina 67
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var dataestudiante = (from e in Datos.Estudiante where id ==
e.Codigo_Estudiante select e).First();
Datos.Estudiante.Remove(dataestudiante);
Datos.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Pgina 68
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Vista Create:
Pgina 69
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Vista Editar:
Vista Detalles:
Pgina 70
FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES
Vista Eliminar:
Referencias bibliogrficas:
http://www.desarrolloweb.com/articulos/que-es-mvc.html
http://blog.en1mes.com/2014/04/mvc-los-programadores-deberian-usarlo/
https://juanlucodingbinding.wordpress.com/2014/03/06/modelo-mvcejemplo-basico-de-mvc-en-asp-net-mvc-4/
http://www.genbetadev.com/formacion/tutorial-de-iniciacion-en-asp-netmvc-con-visual-studio-2013
Pgina 71