Está en la página 1de 71

FACULTAD DE INGENIERA

INGENIERA DE SISTEMAS COMPUTACIONALES

Manual 5.1: MVC 5 Y ENTITY FRAMEWORK EN VISUAL STUDIO 2013


Estimado participante, reciba el saludo cordial de los integrantes de la carrera de
Ingeniera de Sistemas Computacionales de nuestra Universidad Privada del Norte.
Antes de iniciar con la realizacin del manual es necesario que tengas en cuenta lo
siguiente:
MARCO TERICO
a. Qu es un patrn de diseo?
Un patrn de diseo es una solucin reutilizable en problemas con un
contexto comn en el diseo de software. Podemos conceptualizarlo como
una receta, pasos concretos a seguir que nos ayudarn a resolver un
problema. No cualquier cosa puede ser considerada un patrn de
diseo, puesto que deben cumplir ciertos objetivos o tener ciertas
caractersticas:

Reutilizable en distintas circunstancias de diseo.

Efectivo en problemas similares.

Permite evitar riesgos de impidan reutilizar cdigo.

Simplifican la forma de documentar una aplicacin.

b. Patrn de Diseo MVC?


MVC (Modelo-Vista-Controlador) es un patrn de diseo que separa los
datos, la lgica de negocios y las interfaces de usuario. Como su nombre lo
dice, est separado en tres componentes: modelo, controlador y vista. Est
basado en la ideologa de separacin de conceptos y cumple perfectamente
con los objetivos de los patrones de diseo.
c. Modelo
Es la capa encargada de los datos, es decir, tiene mecanismos para acceder
a la informacin y tambin para actualizar su estado. Comnmente se
encarga de comunicarse con la base de datos mediante funciones que
accedern a las tablas y realizarn las funciones habituales de datos.
d. Vista
Se trata del cdigo que nos permitir presentar los datos que el modelo nos
proporciona, como ejemplo podramos decir que en una aplicacin web
es el cdigo HTML que nos permite mostrar la salida de los datos
procesados.

Diseo y Arquitectura de Software

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:

Fig. 1: Modelo MVC

Diseo y Arquitectura de Software

Pgina 2

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

f.

Ventajas de MVC

Est enfocado en separar responsabilidades


Si en este momento ests pensando y eso en que me afecta o
beneficia, pues pensemos un poco en cmo estn creadas las
aplicaciones y sitios web actuales, HTML para los objetos o el
marcado, CSS para el estilo y Javascript para la lgica, cada uno con
su propio enfoque y su propia responsabilidad, pues con MVC es lo
mismo pero incluyendo los componentes que mencionamos antes.

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.

Evitamos cdigo Espagueti


Con este patrn de diseo reducimos y hasta eliminamos el uso de
cdigo de servidor y de presentacin en un mismo lugar.

Perfecto para equipos multidisciplinarios


Con este patrn de diseo reducimos y hasta eliminamos el uso de
cdigo de servidor y de presentacin en un mismo lugar. Por lo que
si en tu equipo hay alguien encargado de maquetar la aplicacin,
alguien ms se encarga de crear las reglas de negocio y dems
actividades, cada uno puede trabajar independientemente del otro
sin sufrir afectaciones.

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.

Diseo y Arquitectura de Software

Pgina 3

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

DESARROLLO
1. Iniciamos el Sistema Operativo Windows.

Fig. 2: Iniciando Windows

2. Iniciamos el IDE (Integrated Development Environment) de Programacin


Visual Studio.

Fig. 3: Iniciando Visual Studio 2013

Diseo y Arquitectura de Software

Pgina 4

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

3. Nos aparece la pantalla inicial de Visual Studio.

Fig. 4: Pantalla Inicial de Visual Studio 2013

4. Creamos un nuevo proyecto.

Ilustracin 1: Creando un nuevo proyecto

Diseo y Arquitectura de Software

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.

Ilustracin 2: Creando la Aplicacin Web ASP.Net

4.-Elegimos la ficha MVC.

Ilustracin 3: Cambiando la autenticacin del Proyecto MVC

Diseo y Arquitectura de Software

Pgina 6

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

5.- Ahora cambiamos la autentificacion a sin autentificacion ya que las otras


opciones es cuando desees que tu proyecto tambien pueda loguearse con tus
cuentas de Facebook, Skype,Twiter. Por ultimo Clic en Aceptar.

Ilustracin 4: Cambiando la autenticacin del proyecto

6.- Luego Seleccionamos MVC y Clic en aceptar.

Ilustracin 5: Creando el proyecto MVC

Diseo y Arquitectura de Software

Pgina 7

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

7.- Observamos que el proyecto se ha creado satisfactoriamente.

Ilustracin 6: Aplicacin Web MVC creada

8.- Abrimos SQL SERVER.

Ilustracin 7: Abriendo SQL Server

Diseo y Arquitectura de Software

Pgina 8

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

9.- Comenzaremos a crear una nueva Base de Datos.

Ilustracin 8: Creando una nueva base de datos

10.- Crearemos la Base de datos Universidad y clic en el botn OK.

Ilustracin 9: Base de Datos Universidad

Diseo y Arquitectura de Software

Pgina 9

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

11.- una vez creada la BD Crearemos una nueva tabla

12.- Ahora crearemos los atributos para la tabla

Diseo y Arquitectura de Software

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

14.- Ahora ese propiedad lo cambiamos a de No a Si

Diseo y Arquitectura de Software

Pgina 11

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

15.- luego procedemos a especificar la clave primaria en este caso elegimos


Codigo_Estudiante ya que ser este atributo por la cual identificaremos cada registro.
Para esto seleccionamos Codigo_Estudiante y nos dirigimos a la llave superior y le
hacemos clic

16.- as que nuestra tabla quedara as:

Diseo y Arquitectura de Software

Pgina 12

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

17.- Ahora procederemos a guardar la tabla

18.- a esta tabla le llamaremos Estudiante

Diseo y Arquitectura de Software

Pgina 13

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

19.- Ahora procederemos a llenar la tabla con registros

20.- Tabla Llenada

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

Pgina 15

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

23.- colocamos un nombre en este caso ModeloUniversidad luego clic en Agregar

24.- Seleccionamos EF Designer desde base de datos y clic en siguiente

Diseo y Arquitectura de Software

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.

26.- escogemos nuestro servidor y nuestra base de datos , luego clic en


Probar Conexin.

Diseo y Arquitectura de Software

Pgina 17

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

27.- como vemos nuestra conexin fue exitosa as que aceptamos y luego clic en
aceptar.

28.- ahora clic en siguiente para seguir

Diseo y Arquitectura de Software

Pgina 18

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

29.- ac podemos escoger el Framework a Trabajar en este caso lo haremos con el


6.x

30.- escogemos nuestra tabla creada y clic en finalizar

Diseo y Arquitectura de Software

Pgina 19

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

31.- nos mostrara la base de datos mapeada

32.- ahora presionamos CTRL + Mayus + S para guardar todo el proyecto .Luego
procederemos a crear nuestro controlador

Diseo y Arquitectura de Software

Pgina 20

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

33.- Escogemos Controlador MVC 5 con acciones de lectura y escritura luego


clic en agregar.

34.- Colocamos un nombre al Controlador y Aceptar

Diseo y Arquitectura de Software

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

36.- Aqu el Cdigo del archivo EstudianteControllers.cs creado


using
using
using
using
using

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();
}

Diseo y Arquitectura de Software

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();
}
}

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

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.

39.- nos quedara de esta manera y luego clic en agregar

Diseo y Arquitectura de Software

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.

41.- Cdigo de nuestro archivo razor creado:


Archivo index.cshtml
@model IEnumerable<DEMO_MVC5.Models.Estudiante>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Codigo_Estudiante)
</th>
<th>
@Html.DisplayNameFor(model => model.Nombre)
</th>
<th>
@Html.DisplayNameFor(model => model.Apellido_Paterno)
</th>
<th>
@Html.DisplayNameFor(model => model.Apellido_Materno)
</th>
<th>
@Html.DisplayNameFor(model => model.Estado)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>

Diseo y Arquitectura de Software

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>

42.- Ahora como ya tenemos nuestro modelo, controlador y vista creada.

Diseo y Arquitectura de Software

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);
}

44.- Nuestro archivo EstudianteController.cs quedara de esta manera


Cdigo Fuente EstudianteController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using 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();
}

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

Pgina 29

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

}
catch
{
return View();
}
}
}
}

45.- Ejecutaremos el proyecto para hacer las pruebas respectivas:

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.

Diseo y Arquitectura de Software

Pgina 30

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

47.- Colocamos un nombre a la vista - escogemos la plantilla crate- y escogemos


la clase modelo estudiante seleccionamos la casilla clic en agregar

Diseo y Arquitectura de Software

Pgina 31

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

48.- tenemos nuestra vista crate creada

Diseo y Arquitectura de Software

Pgina 32

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

49.- Codigo Fuente de vista crate.cshtml


@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">
@Html.LabelFor(model => model.Estado, htmlAttributes: new { @class =
"control-label col-md-2" })

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

Pgina 34

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

50.-al Carga la aplicacin mostrara lo


funciona hacemos clic en Create New

siguiente. Ahora para probar que la vista

51.- Vista Cargada

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

Pgina 36

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

@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("Regresar a Inicio", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

Diseo y Arquitectura de Software

Pgina 37

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

53.- Probando Vista Crate.

54.- Ahora procederemos a ingresarle datos al archivo EstudianteController en la


accin Create.
Este Fragmento de cdigo ser en la accin del post del create.

// 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();
}
}

Diseo y Arquitectura de Software

Pgina 38

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

55.- Ejecutamos para hacer la prueba necesaria:

57.- como vern ya nos muestra el estudiante registrado.

Diseo y Arquitectura de Software

Pgina 39

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

58.-Ahora procederemos a trabajar la accin editar la cual nos permitir actualizar


los datos de los estudiantes.
Para esto nos ubicamos
Estudiante_Controller.cs

en

el

la

accin

GET

en

el

mismo

achivo

59.- Clic derecho y agregamos la vista editar

Diseo y Arquitectura de Software

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

61.- Ahora nos mostrara el archivo edit.cshtml

Diseo y Arquitectura de Software

Pgina 41

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

62.- Cdigo Fuente de Archivo edit.cshtml

@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">

Diseo y Arquitectura de Software

Pgina 42

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

@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="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

Diseo y Arquitectura de Software

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>

Y ahora lo modificaremos para poder


eliminar

llamar a la vista editar y prximamente a

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

Diseo y Arquitectura de Software

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);
}

67.- Ahora nos ubicamos en la accin POST y Colocamos el Siguiente cdigo:


// 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"]);

Diseo y Arquitectura de Software

Pgina 45

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

//Ahora Agregamos a la entidad


Datos.Estudiante.Add(dataestudiante);
// hacemos el guardado
Datos.SaveChanges();
//redireccionamos a la pagina index
return RedirectToAction("Index");
}
catch
{
return View();
}
}

68.- Hasta el momento esto es lo que deberamos tener en nuestro archivo


EstudianteController.cs

Codigo Fuente Archivo EstudianteController.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)
{
return View();
}
// GET: Estudiante/Create
public ActionResult Create()
{
return View();
}
// POST: Estudiante/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try

Diseo y Arquitectura de Software

Pgina 46

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

{ //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();
}
}
// 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

Diseo y Arquitectura de Software

Pgina 47

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

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();
}
}
}
}

69.- Ahora ejecutamos el proyecto para ver que todo corra bien:
Para probar haremos clic en Edit.

Diseo y Arquitectura de Software

Pgina 48

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

70.- Luego modificamos los datos y Hacemos clic en guardar

71.- Vemos los resultados que fueron satisfactorios en el registro nmero 2.

Diseo y Arquitectura de Software

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.

73.- Ahora escogemos la plantilla delete luego como modelo escogemos a


estudiante- seleccionamos el check y clic en agregar.

Diseo y Arquitectura de Software

Pgina 50

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

74.- Tenemos nuestra vista creada delete.cshtml.

75.- Aqu el cdigo Fuente del Archivo delete.cshtml


@model DEMO_MVC5.Models.Estudiante
<h3>Are you sure you want to delete this?</h3>
<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>

Diseo y Arquitectura de Software

Pgina 51

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

@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="Delete" class="btn btn-default" /> |
@Html.ActionLink("Back to List", "Index")
</div>
}
</div>

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
{

Diseo y Arquitectura de Software

Pgina 52

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

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();
}
}

78.- Una vez Modificado procedemos a efectuar la prueba de la vista delete.cshtml


Para eso escogemos un registro y le hacemos clic en delete.

Diseo y Arquitectura de Software

Pgina 53

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

79.- Nos mostrara esta vista de confirmacin de eliminar. Y hacemos clic en eliminar

80.- Como vemos el registro ya fue eliminado

Diseo y Arquitectura de Software

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

82.- escogemos como plantilla la opcin Details luego escogemos el modelo


Estudiante seleccionamos el check y clic en agregar

Diseo y Arquitectura de Software

Pgina 55

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

83.- ac tenemos la vista Details.cshtml creada

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>

Ahora modificamos a esto:


<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.Codigo_Estudiante }) |
@Html.ActionLink("Back to List", "Index")
</p>

85.- El cdigo fuente de la vista details.cshtml debera de quedar as:


@model DEMO_MVC5.Models.Estudiante
<div>
<h4>Estudiante</h4>
<hr />

Diseo y Arquitectura de Software

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>

86.- Ahora nos ubicaremos en la accin Details del archivo


EstudianteController.cs y agregamos el siguiente cdigo:

// GET: Estudiante/Details/5
public ActionResult Details(int id)
{
var dataestudiante = (from e in Datos.Estudiante where id ==
e.Codigo_Estudiante select e).First();

Diseo y Arquitectura de Software

Pgina 57

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

return View(dataestudiante);
}

87.- Ahora ejecutaremos el proyecto y hacemos clic en Details

Diseo y Arquitectura de Software

Pgina 58

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

88.- y como vern nos muestra un resumen del registro seleccionado

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

Pgina 60

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

@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="Registrar" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Regresar a Inicio", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

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>

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

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 }) |

Diseo y Arquitectura de Software

Pgina 64

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

@Html.ActionLink("Regresar a Inicio", "Index")


</p>

Vista ndex:

Cdigo Fuente Index.cshtml


@model IEnumerable<DEMO_MVC5.Models.Estudiante>
<p>
@Html.ActionLink("Nuevo registro", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Codigo_Estudiante)
</th>
<th>
@Html.DisplayNameFor(model => model.Nombre)
</th>
<th>
@Html.DisplayNameFor(model => model.Apellido_Paterno)
</th>
<th>
@Html.DisplayNameFor(model => model.Apellido_Materno)
</th>
<th>
@Html.DisplayNameFor(model => model.Estado)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<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("Editar", "Edit", new { id=item.Codigo_Estudiante }) |
@Html.ActionLink("Detalles", "Details", new { id=item.Codigo_Estudiante }) |
@Html.ActionLink("Eliminar", "Delete", new { id=item.Codigo_Estudiante })

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

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();
}
}
}
}

Diseo y Arquitectura de Software

Pgina 68

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

Ejecucin de cada vista:

Vista Create:

Diseo y Arquitectura de Software

Pgina 69

FACULTAD DE INGENIERA
INGENIERA DE SISTEMAS COMPUTACIONALES

Vista Editar:

Vista Detalles:

Diseo y Arquitectura de Software

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

Diseo y Arquitectura de Software

Pgina 71

También podría gustarte