ASP.NET Core MVC CRUD Menggunakan Entity Framework Core, Bootstrap 4 dan SQL Server

  • Whatsapp
ASP.NET Core MVC CRUD Menggunakan Entity Framework Core, Bootstrap 4 dan SQL Server

Halo dan Selamat Siang!

Artikel ini menunjukkan cara membuat aplikasi ASP.NET Core MVC menggunakan Entity Framework Core Database First, Bootstrap 4, SQL Server, Unit Kerja, dan Pola Desain Repositori. IDE untuk proyek ini adalah Visual Studio 2019 versi 16.9.2. Saya juga menginstal ikon Font Awesome karena glyphicons tidak didukung di Bootstrap 4 dan menerapkan teknik Validasi Model untuk memeriksa data input selama pengiriman formulir.

I. Setup Proyek

1. Buat aplikasi ASP.NET Core MVC yang menargetkan .NET Core 3.1 atau mungkin .NET 5.0 jika Anda telah menginstalnya di komputer Anda.
2. Struktur proyek terdiri dari beberapa folder seperti Pengendali, Akses Data, Model dan Tampilan. Untuk Akses Data, tambahkan dua subfolder lagi yang disebut Repositori dan UnitOfWork. Kita perlu memisahkan antarmuka dan kelas untuk Lapisan Akses Data. Untuk tujuan tutorial ini, saya tidak menambahkan beberapa perpustakaan kelas agar ini tetap sederhana dan mudah.
ASP.NET Core MVC CRUD Menggunakan Entity Framework Core, Bootstrap 4, SQL Server, Unit Kerja Dan Pola Desain Repositori

3. Tambahkan paket NuGet yang diperlukan untuk Entity Framework Core ORM khususnya EntityFrameworkCore, EntityFrameworkCore.SqlServer dan EntityFrameworkCore.Tools. Semuanya mengarah ke versi 5.0.4.

Bacaan Lainnya

ASP.NET Core MVC CRUD Menggunakan Entity Framework Core, Bootstrap 4, SQL Server, Unit Kerja Dan Pola Desain Repositori

4. Sedangkan untuk perpustakaan, saya menginstal versi 5.x font-mengagumkan bersama dengan file validasi jQuery dan jQuery.

ASP.NET Core MVC CRUD Menggunakan Entity Framework Core, Bootstrap 4, SQL Server, Unit Kerja Dan Pola Desain Repositori

5. Berikutnya adalah membuat tabel di database SQL Server Anda karena tutorial ini mengimplementasikan pendekatan Database First.

USE [YourDatabase]
GO

/****** Object: Table [dbo].[Employee] Script Date: 4/7/2021 11:11:47 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[EmployeeGovtID] [varchar](50) NULL,
[EmployeeName] [varchar](200) NULL,
[Age] [int] NULL,
[Address] [nvarchar](max) NULL,
[Salary] [decimal](18, 2) NULL,
[Designation] [varchar](10) NULL,
[HasDependents] [bit] NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

II. Coding Kelas Model

1. Jalankan Scaffold-DBContext di Package Manager Conosle proyek Anda untuk menyambung ke skema database yang baru saja Anda buat sebelumnya. Ini akan merekayasa balik tabel database dan kelas tipe entitas perancah dan kelas DbContext. Setelah menjalankan perintah di bawah ini, ini akan membuat kelas Karyawan dan DBContext di dalam folder Model.

Scaffold-DbContext "Server=Your_Server;Database=Your_Database;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

2. Berikutnya adalah menambahkan kelas EmployeeRecord dengan properti yang identik dengan kelas Karyawan yang berfungsi sebagai Model Tampilan. Properti kelas ini telah didekorasi dengan atribut DataAnnotations dan akan digunakan untuk penyatuan data dengan kontrol Html Razor. Dengan cara ini, saya tidak perlu memanipulasi atau menerapkan perubahan ke kelas yang dihasilkan oleh perintah Scaffhold.

public class EmployeeRecord
{
public int EmployeeId { get; set; }

[Display(Name = "Government ID")]
[Required(ErrorMessage = "Government ID is required")]
public string EmployeeGovtId { get; set; }

[Display(Name = "Employee Name")]
[Required(ErrorMessage = "Name is required")]
public string EmployeeName { get; set; }

[Required(ErrorMessage = "Age is required")]
[Range(0, int.MaxValue, ErrorMessage = "Please enter integer number")]
public int? Age { get; set; }

[Required(ErrorMessage = "Address is required")]
public string Address { get; set; }

[Required]
[Range(1000, 99999.99, ErrorMessage = "Please enter value from 1000 to 99999.99")]
public decimal? Salary { get; set; }

[Required(ErrorMessage = "Designation is required")]
[MinLength(2, ErrorMessage = "Min length of designation is 2 characters")]
public string Designation { get; set; }

[Display(Name = "Has Dependents")]
public bool HasDependents { get; set; }

public string DisplayForDependents
{
get
{
if (HasDependents)
return "Yes";

return "No";
}
}

public EmployeeRecord()
{
EmployeeId = 0;
Address = string.Empty;
Salary = 0;
Age = 0;
Address = string.Empty;
EmployeeName = string.Empty;
Designation = string.Empty;
EmployeeGovtId = string.Empty;
HasDependents = false;
}
}

3. Berikutnya adalah menghapus string koneksi dari kelas DBContext dan mentransfernya di dalam file appsettings.json.

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ASPCoreDB": "Server=Your_Machine;Database=Your_Database;Integrated Security=True"
}
}

AKU AKU AKU. Mengkodekan Kelas dan Antarmuka Akses Data (Repositori dan Unit Kerja)

1. Buat antarmuka bernama IRepository yang berisi deklarasi metode operasi CRUD (Buat, Perbarui, dan Hapus) umum.

 public interface IRepository<T> where T: class
{
T GetByID(int Id);
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> expression);
void Add(T Entity);
void Delete(T Delete);
void Update(T Entity);
}

2. Tambahkan antarmuka repositori lain yang disebut IEmployeeRepository yang mewarisi antarmuka IRepository. Antarmuka ini mungkin berisi definisi metode yang unik untuk entitas karyawan.

 public interface IEmployeeRepository : IRepository<Employee>
{
//you may add other methods here specific to employees.
}

3. Buat kelas repositori generik yang mengimplementasikan metode antarmuka IRepository. Gadis ini berkomunikasi dengan database melalui kelas DBContext dan melakukan operasi CRUD yang sebenarnya menggunakan metode bawaan Entity Framework Core.

public class Repository<T> : IRepository<T> where T : class{
private ASPCoreTestDBContext _context;

public Repository(ASPCoreTestDBContext context)
{
this._context = context;
}

public void Add(T Entity)
{
_context.Set<T>().Add(Entity);
}

public void Delete(T Entity)
{
_context.Set<T>().Remove(Entity);
}

public IEnumerable<T> Find(Expression<Func<T, bool>> expression)
{
return _context.Set<T>().Where(expression);
}

public IEnumerable<T> GetAll()
{
return _context.Set<T>().ToList();
}

public T GetByID(int Id)
{
return _context.Set<T>().Find(Id);
}

public void Update(T Entity)
{
_context.Set<T>().Update(Entity);
}
}

4. Tentukan kelas repositori khusus untuk entitas Karyawan yang mewarisi kelas repositori generik dan antarmuka IEmployeeRepository.

 public class EmployeeRepository : Repository<Employee>, IEmployeeRepository
{
public EmployeeRepository(ASPCoreTestDBContext context) : base(context)
{ }
}

5. Buat antarmuka bernama IUnitOfWork yang mewarisi antarmuka IDisposable dan memiliki properti IEmployeeRepository dengan deklarasi metode get accessor saja dan metode Lengkap yang mengembalikan int.

 public interface IUnitOfWork : IDisposable
{
IEmployeeRepository EmployeeRepository { get; }

int Complete();
}

6. Agar pola Unit Of Work bekerja, buat kelas yang mengimplementasikan antarmuka IUnitOfWork dan memasukkan DBContext ke konstruktornya.

public class UnitOfWork : IUnitOfWork
{
private readonly ASPCoreTestDBContext _context;
public IEmployeeRepository EmployeeRepository { get; private set; }

public UnitOfWork(ASPCoreTestDBContext context)
{
_context = context;
EmployeeRepository = new EmployeeRepository(_context);
}

public int Complete()
{
return _context.SaveChanges();
}

public void Dispose()
{
_context.Dispose();
}
}

7. Dalam metode Startup.cs ConfigureServices (), injeksi ketergantungan terjadi melalui metode AddTransient () dengan langsung menghubungkan jenis layanan (antarmuka) dan implementasinya (kelas). Metode ini juga menetapkan string koneksi untuk kelas DBContext.

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient(typeof(IRepository<>), typeof(Repository<>));
services.AddTransient<IEmployeeRepository, EmployeeRepository>();
services.AddTransient<IUnitOfWork, UnitOfWork>();

var connectionString = Configuration.GetConnectionString("ASPCoreDB");
services.AddDbContext<YourDBContext>(x => x.UseSqlServer(connectionString));

services.AddControllersWithViews();
}

Struktur Akses Data mirip dengan gambar yang disediakan di bawah ini.

ASP.NET Core MVC CRUD Menggunakan Entity Framework Core, Bootstrap 4, SQL Server, Unit Kerja Dan Pola Desain Repositori

IV. Mengkodekan Pengontrol

1. Dalam kelas HomeController.cs Anda, buat bidang pribadi untuk Unit Kerja dan objek DBContext. Variabel ini akan diinisialisasi di konstruktor HomeController. Berikutnya adalah menambahkan metode ActionResult untuk operasi CRUD dan Indeks yang akan menampilkan seluruh catatan karyawan. Objek Unit Of Work merekatkan semuanya dengan memanggil metode CRUD yang ditentukan di kelas Repositori menggunakan fungsi bawaan EFCore.

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private IUnitOfWork _unitOfWork;
private readonly ASPCoreTestDBContext _context;

public HomeController(ILogger<HomeController> logger, IUnitOfWork unitOfWork, ASPCoreTestDBContext context)
{
_logger = logger;
_unitOfWork = unitOfWork;
_context = context;
}

public IActionResult Index()
{
List<EmployeeRecord> model;

model = new List<EmployeeRecord>();

var result = _unitOfWork.EmployeeRepository.GetAll();

if (result.Count() > 0)
{
foreach (var item in result)
{
model.Add(new EmployeeRecord()
{
EmployeeId = item.EmployeeId,
Address = item.Address,
Age = item.Age,
Designation = item.Designation,
EmployeeGovtId = item.EmployeeGovtId,
EmployeeName = item.EmployeeName,
HasDependents = (bool)item.HasDependents,
Salary = item.Salary,
});
}
}

return View(model);
}

[HttpGet]
public IActionResult Create()
{
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(EmployeeRecord employee)
{
Employee empObject;

empObject = new Employee();

if (ModelState.IsValid)
{
empObject.Address = employee.Address;
empObject.Age = employee.Age;
empObject.Designation = employee.Designation;
empObject.EmployeeGovtId = employee.EmployeeGovtId;
empObject.EmployeeName = employee.EmployeeName;
empObject.HasDependents = employee.HasDependents;
empObject.Salary = employee.Salary;

_unitOfWork.EmployeeRepository.Add(empObject);
_unitOfWork.Complete();

return RedirectToAction("Index");
}

return View("Index");
}

[HttpGet]
public IActionResult Edit(int? id)
{
EmployeeRecord model;

model = new EmployeeRecord();

if (id == null)
{
return NotFound();
}

var employee = _unitOfWork.EmployeeRepository.GetByID(Convert.ToInt32(id));

if (employee == null)
{
return NotFound();
}

model.EmployeeId = employee.EmployeeId;
model.Address = employee.Address;
model.Age = employee.Age;
model.Designation = employee.Designation;
model.EmployeeGovtId = employee.EmployeeGovtId;
model.EmployeeName = employee.EmployeeName;
model.HasDependents = (bool)employee.HasDependents;
model.Salary = employee.Salary;

return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(int id, EmployeeRecord employee)
{
Employee empObject;

empObject = new Employee();

if (id != employee.EmployeeId)
{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
empObject.EmployeeId = employee.EmployeeId;
empObject.Address = employee.Address;
empObject.Age = employee.Age;
empObject.Designation = employee.Designation;
empObject.EmployeeGovtId = employee.EmployeeGovtId;
empObject.EmployeeName = employee.EmployeeName;
empObject.HasDependents = employee.HasDependents;
empObject.Salary = employee.Salary;

_unitOfWork.EmployeeRepository.Update(empObject);
_unitOfWork.Complete();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeExists(employee.EmployeeId))
{
return NotFound();
}
else
{
throw;
}
}

return RedirectToAction(nameof(Index));
}

return View(employee);
}

[HttpGet]
public IActionResult Delete(int? id)
{
EmployeeRecord model;

model = new EmployeeRecord();

if (id == null)
{
return NotFound();
}

var employee = _unitOfWork.EmployeeRepository.GetByID(Convert.ToInt32(id));

if (employee == null)
{
return NotFound();
}

model.EmployeeId = employee.EmployeeId;
model.Address = employee.Address;
model.Age = employee.Age;
model.Designation = employee.Designation;
model.EmployeeGovtId = employee.EmployeeGovtId;
model.EmployeeName = employee.EmployeeName;
model.HasDependents = (bool)employee.HasDependents;
model.Salary = employee.Salary;

return View(model);
}

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(int id)
{
var employee = _unitOfWork.EmployeeRepository.GetByID(id);

if (employee != null)
{
_unitOfWork.EmployeeRepository.Delete(employee);
_unitOfWork.Complete();
}

return RedirectToAction(nameof(Index));
}

private bool EmployeeExists(int id)
{
return _unitOfWork.EmployeeRepository.GetByID(id) != null ? true : false;
}

public IActionResult Privacy()
{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}

V. Mengkode Tampilan

1. Layout.cshtml – Referensi file JavaScript dan CSS yang diperlukan seperti jQuery.min.js, jquery.validate.unobtrusive.min.js, jquery.validate.min.js, bootstrap.min.css, fontawesome.css, regular. min.css dan solid.min.css

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - ABC Inc.</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
@* header, container and footer elements here *@
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"></script>
<link rel="stylesheet" href="~/lib/font-awesome/css/fontawesome.css" />
<link rel="stylesheet" href="~/lib/Font-Awesome/css/regular.min.css">
<link rel="stylesheet" href="~/lib/Font-Awesome/css/solid.min.css">
@RenderSection("Scripts", required: false)
</body>
</html>

2. Index.cshtml – Ini akan memuat semua record dan menampilkannya ke tabel. Setiap baris tabel memiliki tombol hapus dan edit yang mengarahkan ke halaman terpisah. Halaman tersebut juga memiliki tombol baru yang mengarahkan ke halaman yang akan menambahkan catatan Karyawan baru.

@model IEnumerable<ASPCoreMVCCrud.Models.EmployeeRecord>

@{
ViewData["Title"] = "Index";
}

<div class="divCompanyHeader">
<h3>ABC Manpower Services Inc. Employee MasterList</h3>
</div>

<div class="row" id="divCreateLink">
<a asp-action="Create" class="btn btn-info">
<i class="fas fa-plus"><span>Add Employee</span></i>
</a>
</div>

<div class="row">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.EmployeeGovtId)
</th>
<th>
@Html.DisplayNameFor(model => model.EmployeeName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.Salary)
</th>
<th>
@Html.DisplayNameFor(model => model.Designation)
</th>
<th>
@Html.DisplayNameFor(model => model.HasDependents)
</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.EmployeeGovtId)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmployeeName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.Salary)
</td>
<td>
@Html.DisplayFor(modelItem => item.Designation)
</td>
<td>
@Html.DisplayFor(modelItem => item.DisplayForDependents)
</td>
<td>
<a asp-action="Edit" title="Edit Employee" asp-route-id="@item.EmployeeId">
<i class="fas fa-edit"></i>
</a>
<a asp-action="Delete" title="Delete Employee" asp-route-id="@item.EmployeeId">
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
}
}
</tbody>
</table>
</div>

@section scripts{
<link href="~/css/Employee.css" rel="stylesheet" />
}

3. Create.cshtml – Tampilan ini bertanggung jawab untuk menambahkan catatan baru ke database. Kelas model yang digunakan dalam tampilan ini adalah EmployeeRecord dengan atribut DataAnnotations yang digunakan dalam memvalidasi input pengguna.

@model ASPCoreMVCCrud.Models.EmployeeRecord

@{
ViewData["Title"] = "Create";
}

<div class="divCompanyHeader">
<h3>Add New Employee Record</h3>
</div>

<hr />
<div class="row">
<div class="col-6">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row">
<label asp-for="EmployeeGovtId" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="EmployeeGovtId" class="form-control" />
<span asp-validation-for="EmployeeGovtId" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="EmployeeName" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="EmployeeName" class="form-control" />
<span asp-validation-for="EmployeeName" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Age" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="Age" class="form-control" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Address" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="Address" class="form-control" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Salary" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="Salary" class="form-control" />
<span asp-validation-for="Salary" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Designation" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="Designation" class="form-control" />
<span asp-validation-for="Designation" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-4">

</div>
<div class="col-8">
<input id="chkDependents" class="form-check-input" type="checkbox" asp-for="HasDependents" />
<span id="spnDependents">Dependents?</span>
</div>
</div>
<div class="form-group row">
<div class="col-4">

</div>
<div class="col-8">
<input type="submit" value="Save" class="btn btn-primary" />
<a asp-action="Index" class="btn btn-info">Back to List</a>
</div>
</div>
</form>
</div>
</div>

@section scripts{
<link href="~/css/Employee.css" rel="stylesheet" />
}

4. Edit.cshtml – Tampilan ini bertanggung jawab untuk mengedit catatan yang ada dari database. Tata letak formulir mirip dengan halaman Buat kecuali bahwa kami memiliki bidang tersembunyi untuk EmployeeID.

@model ASPCoreMVCCrud.Models.EmployeeRecord

@{
ViewData["Title"] = "Edit";
}

<div class="divCompanyHeader">
<h3>Update Employee Record</h3>
</div>
<hr />
<div class="row">
<div class="col-md-6">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="EmployeeId" />
<div class="form-group row">
<label asp-for="EmployeeGovtId" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="EmployeeGovtId" class="form-control" />
<span asp-validation-for="EmployeeGovtId" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="EmployeeName" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="EmployeeName" class="form-control" />
<span asp-validation-for="EmployeeName" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Age" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="Age" class="form-control" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Address" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="Address" class="form-control" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Salary" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="Salary" class="form-control" />
<span asp-validation-for="Salary" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Designation" class="col-4 control-label"></label>
<div class="col-8">
<input asp-for="Designation" class="form-control" />
<span asp-validation-for="Designation" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-4">
</div>
<div class="col-8">
<input asp-for="HasDependents" id="chkDependents" class="form-check-input" type="checkbox" />
<span id="spnDependents">Dependents?</span>
</div>
</div>
<div class="form-group row">
<div class="col-4">
</div>
<div class="col-8">
<input type="submit" value="Update" class="btn btn-primary" />
<a asp-action="Index" class="btn btn-info">Back to List</a>
</div>
</div>
</form>
</div>
</div>

@section scripts{
<link href="~/css/Employee.css" rel="stylesheet" />
}

5. Delete.cshtml – Tampilan ini menunjukkan record yang akan dihapus. Saat dikirim, itu akan memanggil metode Hapus di pengontrol dan menghapus catatan itu dari database menggunakan EmployeeID.

@model ASPCoreMVCCrud.Models.EmployeeRecord

@{
ViewData["Title"] = "Delete";
}

<div class="divCompanyHeader">
<h3>Delete Employee Record?</h3>
</div>
<hr />
<div>
<dl class="row">
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.EmployeeGovtId)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.EmployeeGovtId)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.EmployeeName)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.EmployeeName)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Age)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Age)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Address)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Address)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Salary)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Salary)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Designation)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Designation)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.HasDependents)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.HasDependents)
</dd>
</dl>

<form asp-action="Delete">
<input type="hidden" asp-for="EmployeeId" />
<input type="submit" value="Delete" class="btn btn-danger" />
<a asp-action="Index" class="btn btn-info">Back to List</a>
</form>
</div>

@section scripts{
<link href="~/css/Employee.css" rel="stylesheet" />
}

6. Employee.css – Gaya CSS khusus yang digunakan dalam tampilan.

#divCreateLink {
margin-top: 40px;
margin-bottom: 10px;
color: white !important;
}

#divCreateLink span {
margin-left: 5px;
}

.divCompanyHeader{
margin-top: 50px;
text-align: center;
}

#chkDependents {
margin-left: 0px !important;
}

#spnDependents {
margin-left: 20px;
}

table i{
color: black;
}

VI. Membungkus

Dalam posting ini, kita belajar cara membuat situs web ASP.NET Core MVC CRUD menggunakan Entity Framework Core 5, SQL Server dan Bootstrap 4. Tutorial ini juga menggunakan font. Yang perlu kita lakukan saat mengikuti tutorial ini adalah memastikan untuk memperbarui nilai string koneksi dengan database dan server Anda. Selain itu, Anda perlu mengganti DBContext dan nama namespace dari file yang Anda buat.

ASP.NET Core MVC CRUD Menggunakan Entity Framework Core, Bootstrap 4, SQL Server, Unit Kerja Dan Pola Desain Repositori

Pos terkait

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *