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>
}
miércoles, 22 de abril de 2020
MVC C# Usando ADO.Net framework
Nuevo Proyecto
C#
Web Aplicacion web ASP.Net
Nombre MVC C#
Elegimos MVC
Y Vemos que la casilla mvc se activa
Autenticacion = Sin Autenticacion
Desactivamos la casilla host in the cloud
Click derecho al explorador de soluciones
Elegimos ADO.NET Entity Data Model El Nombre BasedatosDataModel
Elegimos EF Designer desde base de datos
click en siguiente
Elegimos el host
Damos el nombre del servidor
Autenticacion SQLServer
Nombre y contraseña y elegimos la bd
Activamos el radiobuton Si, incluir la cadena de conexion
Selecionamos las tablas
Click derecho al explorador de soluciones y elegimos Limpiar proyecto y recompilar solucion
Click derecho en la carpeta Controladores agregar Controlador
Elegimos Controlador de MVC 5 con vistas que usa Entity Framework
Agregamos el usuario de base de datos
y la base de datos
Agregamos otro controlador MVC 5
Vamos a Vistas y abrimos la carpeta Home y abrimos index.cshtml
en <h2>
<h2>@Html.ActionLink("Alumnos","Index","tblagendas")</h2>
Actualizamos
Limpiamos y Recompilamos
En la carpeta Views seleccionamos la carpeta tblagenda
y nos dirigimos a index.cshtml
Podemos modificar
Los link Teniendo en cuenta que el primer parametro es el nombre del link
@Html.ActionLink("Nuevo", "Create")
C#
Web Aplicacion web ASP.Net
Nombre MVC C#
Elegimos MVC
Y Vemos que la casilla mvc se activa
Autenticacion = Sin Autenticacion
Desactivamos la casilla host in the cloud
Click derecho al explorador de soluciones
Elegimos ADO.NET Entity Data Model El Nombre BasedatosDataModel
Elegimos EF Designer desde base de datos
click en siguiente
Elegimos el host
Damos el nombre del servidor
Autenticacion SQLServer
Nombre y contraseña y elegimos la bd
Activamos el radiobuton Si, incluir la cadena de conexion
Selecionamos las tablas
Click derecho al explorador de soluciones y elegimos Limpiar proyecto y recompilar solucion
Click derecho en la carpeta Controladores agregar Controlador
Elegimos Controlador de MVC 5 con vistas que usa Entity Framework
Agregamos el usuario de base de datos
y la base de datos
Agregamos otro controlador MVC 5
Vamos a Vistas y abrimos la carpeta Home y abrimos index.cshtml
en <h2>
<h2>@Html.ActionLink("Alumnos","Index","tblagendas")</h2>
Actualizamos
Limpiamos y Recompilamos
En la carpeta Views seleccionamos la carpeta tblagenda
y nos dirigimos a index.cshtml
Podemos modificar
Los link Teniendo en cuenta que el primer parametro es el nombre del link
@Html.ActionLink("Nuevo", "Create")
martes, 21 de abril de 2020
WCF C# CRUD
Vamos a crear un WCF en C#
Creamos la base de datos bdagenda y la tabla tblagenda
Usaremos Visual Studio 2017 y SQL Server 2008
Creamos la base de datos bdagenda y la tabla tblagenda
Usaremos Visual Studio 2017 y SQL Server 2008
IService1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfService1
{
// NOTA: puede usar el comando "Rename" del menú "Refactorizar"
para cambiar el nombre de interfaz "IService1" en el código y en el
archivo de configuración a la vez.
[DataContract]
public class myAgenda
{
int _Id;
string
_Nombre;
string
_Apellidos;
string _Telefono;
string
_Correo;
[DataMember]
public int Id
{
get { return _Id; }
set { _Id = value; }
}
[DataMember]
public string
Nombre
{
get { return _Nombre; }
set { _Nombre = value; }
}
[DataMember]
public string
Apellidos
{
get { return _Apellidos; }
set { _Apellidos = value; }
}
[DataMember]
public string Telefono
{
get { return _Telefono; }
set { _Telefono = value; }
}
[DataMember]
public string
Correo
{
get { return _Correo; }
set { _Correo = value; }
}
}
[ServiceContract]
public
interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
[OperationContract]
int NuevoContacto(myAgenda
agenda);
[OperationContract]
int EditarContacto(myAgenda
agenda);
[OperationContract]
int EliminarContacto(int idContacto);
[OperationContract]
myAgenda buscarContacto(int idContacto);
[OperationContract]
List<myAgenda> mostrarContactos();
// TODO: agregue aquí sus operaciones de servicio
}
// Utilice un contrato de datos, como se ilustra en el ejemplo
siguiente, para agregar tipos compuestos a las operaciones de servicio.
[DataContract]
public class CompositeType
{
bool boolValue =
true;
string stringValue =
"Hello
";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
--------------------------------------------------------------------------------
Service1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WcfService1
{
// NOTA: puede usar el comando "Rename" del menú "Refactorizar"
para cambiar el nombre de clase "Service1" en el código, en svc y en
el archivo de configuración.
// NOTE: para iniciar el Cliente de prueba WCF para probar este
servicio, seleccione Service1.svc o Service1.svc.cs en el Explorador de
soluciones e inicie la depuración.
public class
Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered:
{0}", value);
}
string cadenaConexion = ConfigurationManager.ConnectionStrings["myConexion"].ConnectionString;
// /*
//CREATE PROCEDURE _spIAContacto(
// @operacion varchar(1),
// @dId int,
// @dNombre varchar(50),
// @dApellidos varchar(100),
// @dTelefono varchar(15),
// @dCorreo varchar(100)
//)
//AS
// if @operacion='I'/* Insertar */
// insert into tblAgenda(Nombre,Apellidos,Telefono,Correo)values(@dNombre,@dApellidos,@dTelefono,@dCorreo)
//else if @operacion='A'/*
Insertar */
// update tblAgenda set
Nombre=@dNombre,
Apellidos=@dApellidos, Telefono=@dTelefono,Correo=@dCorreo) Where
Id=@Id
public int NuevoContacto(myAgenda
agenda)
{
int res = 0;
try
{
SqlConnection cnn =
new SqlConnection(cadenaConexion);
cnn.Open();
SqlCommand cmd = new SqlCommand("_spIAContacto",
cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@operacion",
"I");
cmd.Parameters.AddWithValue("@dId",
0);
cmd.Parameters.AddWithValue("@dNombre",
agenda.Nombre);
cmd.Parameters.AddWithValue("@dApellidos",
agenda.Apellidos);
cmd.Parameters.AddWithValue("@dTelefono",
agenda.Telefono);
cmd.Parameters.AddWithValue("@dCorreo",
agenda.Correo);
res = cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
throw new Exception("Error al insertar", ex);
}
return res;
}
public int EditarContacto(myAgenda
agenda)
{
int res = 0;
try
{
SqlConnection cnn =
new SqlConnection(cadenaConexion);
cnn.Open();
SqlCommand cmd = new SqlCommand("_spIAContacto",
cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@operacion",
"A");
cmd.Parameters.AddWithValue("@dId",
agenda.Id);
cmd.Parameters.AddWithValue("@dNombre",
agenda.Nombre);
cmd.Parameters.AddWithValue("@dApellidos",
agenda.Apellidos);
cmd.Parameters.AddWithValue("@dTelefono",
agenda.Telefono);
cmd.Parameters.AddWithValue("@dCorreo",
agenda.Correo);
res = cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
throw new Exception("Error al modificar", ex);
}
return res;
}
// CREATE PROCEDURE -spContactoSE(
// @operacion varchar(1),
// @dId int
//)as
//if @operacion ='S'
/*Seleccionar un Registro*/
//select * from tblAgenda where Id=@dId
//else
//if @operacion ='E'
/* Eliminar */
// delete from tblAgenda where Id=@dId
//else
// select * from TblAgenda
public int EliminarContacto(int idContacto)
{
int res = 0;
try
{
SqlConnection cnn =
new SqlConnection(cadenaConexion);
cnn.Open();
SqlCommand cmd = new SqlCommand("spContactoSE",
cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@operacion",
"E");
cmd.Parameters.AddWithValue("@dId",
idContacto);
res = cmd.ExecuteNonQuery();
cnn.Close();
}
catch (Exception ex)
{
throw new Exception("Error al eliminar", ex);
}
return res;
}
public myAgenda buscarContacto(int idContacto)
{
myAgenda newAgenda = new myAgenda();
try
{
SqlConnection cnn =
new SqlConnection(cadenaConexion);
cnn.Open();
SqlCommand cmd = new SqlCommand("spContactoSE",
cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@operacion",
"S");
cmd.Parameters.AddWithValue("@dId",
idContacto);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
if (rd.Read())
{
newAgenda.Id =
rd.GetInt32(0);
newAgenda.Nombre = rd.GetString(1);
newAgenda.Apellidos = rd.GetString(2);
newAgenda.Telefono = rd.GetString(3);
newAgenda.Correo = rd.GetString(4);
}
}
else
{
return newAgenda;
throw new Exception("No
hay Registros");
}
cnn.Close();
}
catch (Exception ex)
{
throw new Exception("Error al buscar contacto",
ex);
}
return newAgenda;
}
public List<myAgenda> mostrarContactos()
{
List<myAgenda> lista = new List<myAgenda>();
try
{
SqlConnection cnn =
new SqlConnection(cadenaConexion);
cnn.Open();
SqlCommand cmd = new SqlCommand("spContactoSE",
cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@operacion",
"");
cmd.Parameters.AddWithValue("@dId",
"");
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
lista.Add(new myAgenda
{
Id =
rd.GetInt32(0),
Nombre = rd.GetString(1),
Apellidos = rd.GetString(2),
Telefono = rd.GetString(3),
Correo = rd.GetString(4),
});
}
}
else
{
return
lista;
throw new Exception("No
hay Registros");
}
cnn.Close();
}
catch (Exception ex)
{
throw new Exception("Error al buscar contacto",
ex);
}
return lista;
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue +=
"Suffix";
}
return composite;
}
}
}
Ahora configuramos la conexion en el archivo Web.config
<connectionStrings>
<add name="myconexion"
connectionString="data
source=CHARLY-PC\SQLEXPRESS;initial catalog =bdagenda;integrated security
=true;"/>
</connectionStrings>
Escriba el ID del contacto txtid btnbuscar
lblmensaje
Nombre txtnombre.Text
Apellidos txtapellidos.Text
Telefono txttelefono.Text
Correo txtcorreo.Text
btnnuevo btneditar btneliminar
btnmostrartodos
<EmptyDataTemplate>No
hay datos disponibles</EmptyDataTemplate>
y por ultimo ponemos los metodos dentro de cada boton
protected void btnbuscar_Click(object sender, EventArgs e)
{
Service1 cliente = new Service1();
myAgenda agenda = new myAgenda();
int id;
id = Convert.ToInt32(this.txtid.Text);
if (txtid.Text.Trim() !=
"")
{
agenda = cliente.buscarContacto(id);
if (agenda.Nombre == null) {
this.lblmensaje.Text =
"No existe el id";
txtnombre.Text =
"";
txtapellidos.Text =
"";
txttelefono.Text =
"";
txtcorreo.Text =
"";
}
else {
txtnombre.Text = agenda.Nombre;
txtapellidos.Text = agenda.Apellidos;
txttelefono.Text = agenda.Telefono;
txtcorreo.Text = agenda.Correo;
}
}
else {
lblmensaje.Text =
"Escriba el id";
}
}
protected void btnmostrartodos_Click(object sender, EventArgs e)
{
Service1 cliente = new Service1();
GridView1.DataSource = cliente.mostrarContactos();
GridView1.DataBind();
}
protected void btnnuevo_Click(object sender, EventArgs e)
{
Service1 cliente = new Service1();
myAgenda agenda = new myAgenda();
agenda.Nombre = this.txtnombre.Text;
agenda.Apellidos = this.txtapellidos.Text;
agenda.Correo = this.txtcorreo.Text;
agenda.Telefono = this.txttelefono.Text;
if (cliente.NuevoContacto(agenda)
> 0)
{
lblmensaje.Text =
"Los datos se guardaron con exito";
}
}
protected void btneditar_Click(object sender, EventArgs e)
{
Service1 cliente = new Service1();
myAgenda agenda = new myAgenda();
agenda.Id = Convert.ToInt32(this.txtid.Text);
agenda.Nombre = this.txtnombre.Text;
agenda.Apellidos = this.txtapellidos.Text;
agenda.Correo = this.txtcorreo.Text;
agenda.Telefono = this.txttelefono.Text;
if (cliente.EditarContacto(agenda)
> 0)
{
lblmensaje.Text =
"Contacto actualizado con exito";
}
}
protected void btneliminar_Click(object sender, EventArgs e)
{
Service1 cliente = new Service1();
myAgenda agenda = new myAgenda();
agenda.Id = Convert.ToInt32(this.txtid.Text);
if (cliente.EliminarContacto(agenda.Id)
> 0)
{
lblmensaje.Text =
"Se elimino con exito";
}
}
Suscribirse a:
Comentarios (Atom)









