ASP.NET Core MVC - CRUD usando leiaute AdminLTE - II
Neste artigo vamos realizar um CRUD básico em uma aplicação ASP .NET Core MVC usando o leiaute do template AdminLTE. |
Continuando a primeira parte do artigo vamos definir o acesso e a manutenção dos dados dos pacientes em nossa aplicação ASP .NET Core.
Criando o controlador PacientesController e as Views do projeto
Selecione a pasta Controllers e clique com o botão direito do mouse selecionando a opção Add-> Controller;
Na janela Add New Scaffolded item , selecione a opção MVC Controller with views, using Entity Framweork e clique no botão Add;
Na próxima janela selecione as seguintes opções:
Marque as demais opções conforme a figura abaixo e clique em Add:
Ao final será criado o controlador PacientesController e as respectivas Views na pasta Views/Pacientes.
Abaixo temos o código do controlador:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using AspnAdminLte_Crud.Models;
namespace AspnAdminLte_Crud.Controllers
{
public class PacientesController : Controller
{
private readonly AppDbContext _context;
public PacientesController(AppDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index(string? searchString)
{
if (searchString != null)
{
var pacientes = from m in _context.Pacientes
select m;
if (!String.IsNullOrEmpty(searchString))
{
pacientes = pacientes.Where(s => s.Nome.Contains(searchString));
}
return View(await pacientes.ToListAsync());
}
else
{
return View(await _context.Pacientes.ToListAsync());
}
}
//// GET: Pacientes
//public async Task<IActionResult> Index()
//{
// return View(await _context.Pacientes.ToListAsync());
//}
// GET: Pacientes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var paciente = await _context.Pacientes
.FirstOrDefaultAsync(m => m.PacienteId == id);
if (paciente == null)
{
return NotFound();
}
return View(paciente);
}
// GET: Pacientes/Create
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("PacienteId,Nome,Email,Telefone,Clinica,DataCadastro")]
Paciente paciente)
{
if (ModelState.IsValid)
{
_context.Add(paciente);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(paciente);
}
// GET: Pacientes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var paciente = await _context.Pacientes.FindAsync(id);
if (paciente == null)
{
return NotFound();
}
return View(paciente);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("PacienteId,Nome,Email,Telefone,Clinica,DataCadastro")]
Paciente paciente)
{
if (id != paciente.PacienteId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(paciente);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PacienteExists(paciente.PacienteId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(paciente);
}
// GET: Pacientes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var paciente = await _context.Pacientes
.FirstOrDefaultAsync(m => m.PacienteId == id);
if (paciente == null)
{
return NotFound();
}
return View(paciente);
}
// POST: Pacientes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var paciente = await _context.Pacientes.FindAsync(id);
_context.Pacientes.Remove(paciente);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool PacienteExists(int id)
{
return _context.Pacientes.Any(e => e.PacienteId == id);
}
}
}
|
Este é o código padrão gerado pelo Scaffold e usa o EF Core para realizar a persistência. Poderíamos implementar um repositório para desacoplar a camada de acesso a dados do ORM para melhorar o nosso projeto.
O código acima já mostra o método Action Index já ajustado para realizar a busca dinâmica.
Abaixo destacamos o código da Action Index onde estamos recebendo uma string que é o critério de busca para localizar os pacientes pelo nome:
... public async Task<IActionResult> Index(string? searchString)
{
if (searchString != null)
{
var pacientes = from m in _context.Pacientes
select m;
if (!String.IsNullOrEmpty(searchString))
{
pacientes = pacientes.Where(s => s.Nome.Contains(searchString));
}
return View(await pacientes.ToListAsync()); } else { return View(await _context.Pacientes.ToListAsync()); } } ... |
O parâmetro searchString é opcional sendo passado pelo formulário de busca.
Para poder implementar a funcionalidade de procurar pelo nome do paciente vamos alterar o código do arquivo _Layout.cshtml na pasta /Views/Shared conforme mostram as linhas em azul:
...
<form action="/Pacientes/Index" method="get" class="sidebar-form"> <div class="input-group"> <input type="text" name="searchString" class="form-control" placeholder="Procurar..."> <span class="input-group-btn"> <button type="submit" name="search" id="search-btn" class="btn btn-flat"> <i class="fa fa-search"></i> </button> </span> </div> </form> <!-- /.search form --> <!-- Sidebar Menu --> @Html.Partial("_MainMenu") ... |
No código submetemos o formulário com o critério de busca informado em searchString para a Action Index do controlador Pacientes.
Existem outros ajustes visuais que devemos fazer nas views mas apenas para dar um apelo estético.
Executando o projeto neste momento iremos obter o seguinte resultado:
Pronto !!!
Configuramos o template para exibir em nossa aplicação ASP .NET Core MVC um painel com imagens, menus e uma caixa de busca e já temos tudo funcionando, inclusive o CRUD básico.
Pegue o projeto aqui (sem os arquivos do AdminLTE): AspnAdminLte_Crud.zip
"Porque o
Senhor é justo, e ama a justiça; o seu rosto olha para os retos."
Salmos 11:7
Referências:
Super DVD Vídeo Aulas - Vídeo Aula sobre VB .NET, ASP .NET e C#
Super DVD C# - Recursos de aprendizagens e vídeo aulas para C#
ASP .NET Core 2 - MiniCurso Básico - Macoratti
ASP .NET Core - Macoratti
Conceitos - .NET Framework versus .NET Core - Macoratti
ASP .NET Core - Conceitos Básicos - Macoratti.net
ASP .NET Core MVC - CRUD básico com ADO .NET - Macoratti
ASP .NET Core - Implementando a segurança com ... - Macoratti.net
ASP .NET Core - Apresentando Razor Pages - Macoratti