ASP.NET Full CRUD Operation Using .NET 7.0
--
In ASP.NET, performing CRUD (Create, Read, Update, Delete) operation is a fundamental aspect of building web applications that interact with a database. Here’s a step-by-step guide to implementing CRUD operations using ASP.NET Core, which is a modern and cross-platform framework for building web applications.
Assuming you have an ASP.NET Core MVC application set up, let’s go through each CRUD operation:
Create (Insert):
- Create a model class: Define a C# class that represents the entity you want to work with. This class will typically map to a database table.
public class Category: EntityBase
{
public Int64 Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
}
public class EntityBase
{
[Display(Name = "Created Date")]
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public bool Cancelled { get; set; }
}
Create a controller: Add a controller to handle CRUD operations for your model. Use scaffolding or create one manually.
public class CategoriesController : Controller
{
private readonly ApplicationDbContext _context;
public CategoriesController(ApplicationDbContext context)
{
_context = context;
}
}
Read (Retrieve):
Display data: Create a view to display the list of Categories or details of a single Category.
[HttpGet]
public async Task<IActionResult> Details(long? id)
{
if (id == null) return NotFound();
var vm = await _context.Category.FirstOrDefaultAsync(m => m.Id == id);
if (vm == null) return NotFound();
return PartialView("_Details", vm);
}
Create a view to display the data. For example, create a view named Index.cshtml
in the Views/Categories
folder.
@{
ViewData["title"] = "Categories";
}
<div class="row">
<div class="col-md-5">
<button class="btn btn-sm btn-danger" onclick="AddEdit(0)">Add New</button>
</div>
<div class="col-md-7 pull-right">
<h5 class="pull-right"><b> Categories List</b></h5>
</div>
</div>
<hr />
<table id="tblCategories" class="BlueGreen"></table>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/js/Categories/Categories_CRUD.js"></script>
<script src="~/js/Categories/Categories_Datatable.js"></script>
Update (Edit):
Create an Edit view for updating existing records. Add an action method in your controller to handle the update operation.
[HttpPost]
public async Task<IActionResult> AddEdit(Category vm)
{
JsonResultViewModel _JsonResultViewModel = new();
try
{
if (ModelState.IsValid)
{
Category _Categories = new();
if (vm.Id > 0)
{
_Categories = await _context.Category.FindAsync(vm.Id);
vm.CreatedDate = _Categories.CreatedDate;
vm.CreatedBy = _Categories.CreatedBy;
vm.ModifiedDate = DateTime.Now;
vm.ModifiedBy = HttpContext.User.Identity.Name;
_context.Entry(_Categories).CurrentValues.SetValues(vm);
await _context.SaveChangesAsync();
_JsonResultViewModel.AlertMessage = "Category Updated Successfully. ID: " + _Categories.Id;
_JsonResultViewModel.IsSuccess = true;
return new JsonResult(_JsonResultViewModel);
}
else
{
_Categories = vm;
_Categories.CreatedDate = DateTime.Now;
_Categories.ModifiedDate = DateTime.Now;
_Categories.CreatedBy = HttpContext.User.Identity.Name;
_Categories.ModifiedBy = HttpContext.User.Identity.Name;
_context.Add(_Categories);
await _context.SaveChangesAsync();
_JsonResultViewModel.AlertMessage = "Category Created Successfully. ID: " + _Categories.Id;
_JsonResultViewModel.IsSuccess = true;
return new JsonResult(_JsonResultViewModel);
}
}
_JsonResultViewModel.AlertMessage = "Operation failed.";
_JsonResultViewModel.IsSuccess = false;
return new JsonResult(_JsonResultViewModel);
}
catch (Exception ex)
{
_JsonResultViewModel.IsSuccess = false;
_JsonResultViewModel.AlertMessage = ex.Message;
return new JsonResult(_JsonResultViewModel);
throw;
}
}
Delete:
- Add a Delete action method to your controller to handle item deletion.
[HttpDelete]
public async Task<JsonResult> Delete(Int64 id)
{
try
{
var _Categories = await _context.Category.FindAsync(id);
_Categories.ModifiedDate = DateTime.Now;
_Categories.ModifiedBy = HttpContext.User.Identity.Name;
_Categories.Cancelled = true;
_context.Update(_Categories);
await _context.SaveChangesAsync();
return new JsonResult(_Categories);
}
catch (Exception)
{
throw;
}
}
Remember to configure your ASP.NET Core application to work with a database and have an instance of the database context (ApplicationDbContext
in the examples above) injected into your controllers. Additionally, set up routing and views to properly navigate between different CRUD operations.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<Category> Category { get; set; }
}
This is a simplified overview of implementing CRUD operations in ASP.NET Core. In a real-world application, you would also need to handle validation, error handling, and authentication/authorization, among other considerations.
🚀 Complete Project and ASP.NET Full Stack Development Series
In summary, ASP.NET is a reliable choice for building web applications with CRUD functionality. Its rich feature set, security measures, cross-platform support, and strong community make it a popular framework for a wide range of web development projects. However, it’s essential to stay up-to-date with the latest ASP.NET developments and best practices as the technology continues to evolve.