miércoles, 29 de abril de 2020

CRUD MVC Ado.NetFramework Controlador en blanco


Herramienta a utilizar: Visual Studio 2017 y Sql Server 2008

Vamos a crear una base de datos con su respectiva tabla de ejemplo:

create database bdagenda
usebdagenda

create table tblagenda(
Id int Identity(1,1) Primary Key,
Nombre varchar(60),
Apellidos varchar(60),
Telefono varchar(60),
Correo varchar(60)
)

En Visual Studio 2017
Archivo ->Nuevo -> Proyecto-> Web->Aplicacion web ASP.Net Framework->MVC
La aplicacion se va a llamar MVCCRUDFramework.

Click Derecho en el proyecto-> Agregar ->Nuevo Elemento-> Data- ADO.NET Entity Data Model
Elegimos la base de datos y la tabla.

Creamos una carpeta llamada  Models y dentro de ella otra carpeta llamada ViewModels
Agregamos dos clases
un llamada
ListtblagendaViewModels  la cual va a contener
 public class ListtblagendaViewModels
    {

        public int Id { get; set; }
        public string Nombre { get; set; }
        public string Apellidos { get; set; }
        public string Telefono { get; set; }
        public string Correo { get; set; }

    }

y la otra llamada tblagendaViewModel que va a contener lo siguiente.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVCCRUDFramework.Models.ViewModels
{
    public class tblagendaViewModel
    {
        public int Id { get; set; }

        [Required]
        [StringLength(60)]
        [Display(Name = "Nombre")]
        public string Nombre { get; set; }

        [Required]
        [StringLength(60)]
        [Display(Name = "Apellidos")]
        public string Apellidos { get; set; }

        [Required]
        [Display(Name = "Telefono")]
        public string Telefono { get; set; }

        [Required]
        [EmailAddress]
        [Display(Name = "Correo")]
        public string Correo { get; set; }

        //En caso de fecha
        //[Required]
        //[DataType(DataType.Date)]
        //[Display(Name = "Fecha de nacimiento")]
        //[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        //public DateTime Fecha_Nacimiento { get; set; }
    }
}


Ahora Abrimos la Carpeta Content
BORRAMOS TODO
Y agregamos lo siguiente:
.red {
    color: red;
   
}

Click derecho en la carpeta Controller -> Agregar -> Controlador-> Elegimos Controlador MVC 5 En blanco
y Escribimos el codigo:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCCRUDFramework.Models;
using MVCCRUDFramework.Models.ViewModels;

namespace MVCCRUDFramework.Controllers
{
    public class tblagendaController : Controller
    {
        // GET: tblagenda
        public ActionResult Index()
        {


            List<ListtblagendaViewModels> lst;
            using (conexionbdagendaEntities db = new conexionbdagendaEntities())
            {
                 lst = (from d in db.tblagenda
                           select new ListtblagendaViewModels
                           {
                               Id = d.Id,
                               Nombre = d.Nombre,
                               Apellidos = d.Apellidos,
                               Telefono = d.Telefono,
                               Correo = d.Correo
                           }).ToList();

            }
            return View(lst);
        }

        public ActionResult Nuevo()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Nuevo(tblagendaViewModel model)
        {

            try
            {
                if (ModelState.IsValid)
                {
                    using (conexionbdagendaEntities db = new conexionbdagendaEntities())
                    {
                        var otblag = new tblagenda();
                        otblag.Nombre = model.Nombre;
                        otblag.Apellidos = model.Apellidos;
                        otblag.Telefono = model.Telefono;
                        otblag.Correo = model.Correo;
                        db.tblagenda.Add(otblag);
                        db.SaveChanges();
                    }
                    return Redirect("~/tblagenda/");
                }

                return Redirect("~/tblagenda/");
                //return View(model);

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }


        public ActionResult Editar(int Id)
        {
            tblagendaViewModel model = new tblagendaViewModel();
            using (conexionbdagendaEntities db = new conexionbdagendaEntities())
            {
                var otblag = db.tblagenda.Find(Id);
                model.Nombre = otblag.Nombre;
                model.Apellidos = otblag.Apellidos;
                model.Telefono = otblag.Telefono;
                model.Correo = otblag.Correo;
                model.Id = otblag.Id;

            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Editar(tblagendaViewModel model)
        {

            try
            {
                if (ModelState.IsValid)
                {
                    using (conexionbdagendaEntities db = new conexionbdagendaEntities())
                    {
                        var otblag = db.tblagenda.Find(model.Id);
                        otblag.Nombre = model.Nombre;
                        otblag.Apellidos = model.Apellidos;
                        otblag.Telefono = model.Telefono;
                        otblag.Correo = model.Correo;

                        db.Entry(otblag).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                    return Redirect("~/tblagenda/");
                }

                return Redirect("~/tblagenda/");
                //return View(model);

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }



        [HttpGet]
        public ActionResult Eliminar(int Id)
        {
           
            using (conexionbdagendaEntities db = new conexionbdagendaEntities())
            {
                var otblag = db.tblagenda.Find(Id);
                db.tblagenda.Remove(otblag);
                db.SaveChanges();
            }
           
            return Redirect("~/tblagenda/");
        }


    }
   
}




Por cada metodo Agregamos una vista , damos click derechoen el nombre del metodo y agregamos la vista.


La vista Index va a contener lo siguiente

@model List<MVCCRUDFramework.Models.ViewModels.ListtblagendaViewModels>

@{
    ViewBag.Title = "Mis datos";
}

<h2>@ViewBag.Title</h2>


<div class="row" style="text-align:right;padding:5px;">
    <a href="~/tblagenda/Nuevo" class="btn btn-primary"> Nuevo</a>
    <div class="col-md-12">
        <table class="table">
            <tr>
                <th>#</th>
                <th>Nombre</th>
                <th>Apellidos</th>
                <th>Telefono</th>
                <th>Correo</th>
            </tr>
            @foreach (var oElemento in Model)
            {
            <tr>
                <td>@oElemento.Id</td>
                <td>@oElemento.Nombre</td>
                <td>@oElemento.Apellidos</td>
                <td>@oElemento.Telefono</td>
                <td>@oElemento.Correo</td>
                <td>
                    <a class="btn  btn-default" href="~/tblagenda/Editar/@oElemento.Id">Editar</a>
                    <a class="btn  btn-danger" href="~/tblagenda/Eliminar/@oElemento.Id">Eliminar</a>
                   
                </td>
            </tr>

            }
        </table>
    </div>
</div>



La vista Nuevo va a contener lo siguiente:


@model MVCCRUDFramework.Models.ViewModels.tblagendaViewModel
@{
    ViewBag.Title = "Nuevo";
}

<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("Nuevo","tblagenda",FormMethod.Post))
{
    <div class="row">
        <div class="col-md-12">
            <div>
                @Html.LabelFor(d => d.Nombre)
                @Html.TextBoxFor(d => d.Nombre, "", new { @class = "form-control" })
                @Html.ValidationMessageFor(d => d.Nombre, null, new { @class = "red" })
            </div>
            <div>
                @Html.LabelFor(d => d.Apellidos)
                @Html.TextBoxFor(d => d.Apellidos, "", new { @class = "form-control" })
                @Html.ValidationMessageFor(d => d.Apellidos, null, new { @class = "red" })
            </div>
            <div>
                @Html.LabelFor(d => d.Telefono)
                @Html.TextBoxFor(d => d.Telefono, "", new { @class = "form-control" })
                @Html.ValidationMessageFor(d => d.Telefono, null, new { @class = "red" })
            </div>
            <div>
                @Html.LabelFor(d => d.Correo)
                @Html.TextBoxFor(d => d.Correo, "", new { @class = "form-control" })
                @Html.ValidationMessageFor(d => d.Correo, null, new { @class = "red" })
            </div>
            <br />
            <div style="text-align:right">
                <input value="Guardar" class="btn btn-primary" type="submit" />
            </div>

        </div>
    </div>
}

y la vista Editar va a tener



@model MVCCRUDFramework.Models.ViewModels.tblagendaViewModel
@{
    ViewBag.Title = "Editar";
}

<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("Editar", "tblagenda", FormMethod.Post))
{
    <div class="row">
        <div class="col-md-12">
            @Html.HiddenFor(d => d.Id)
            <div>
                @Html.LabelFor(d => d.Nombre)
                @Html.TextBoxFor(d => d.Nombre, "", new { @class = "form-control" })
                @Html.ValidationMessageFor(d => d.Nombre, null, new { @class = "red" })
            </div>
            <div>
                @Html.LabelFor(d => d.Apellidos)
                @Html.TextBoxFor(d => d.Apellidos, "", new { @class = "form-control" })
                @Html.ValidationMessageFor(d => d.Apellidos, null, new { @class = "red" })
            </div>
            <div>
                @Html.LabelFor(d => d.Telefono)
                @Html.TextBoxFor(d => d.Telefono, "", new { @class = "form-control" })
                @Html.ValidationMessageFor(d => d.Telefono, null, new { @class = "red" })
            </div>
            <div>
                @Html.LabelFor(d => d.Correo)
                @Html.TextBoxFor(d => d.Correo, "", new { @class = "form-control" })
                @Html.ValidationMessageFor(d => d.Correo, null, new { @class = "red" })
            </div>
            <br />
            <div style="text-align:right">
                <input value="Guardar" class="btn btn-primary" type="submit" />
            </div>

        </div>
    </div>
}



No hay comentarios:

Publicar un comentario