C# : ASP.NET MVC Development: CRUD Operations, Paging, Sorting, and Searching

ASP.NET MVC is a powerful framework for building web applications, providing developers with tools for creating full-stack solutions. In this comprehensive guide, we'll cover the implementation of CRUD operations (Create, Read, Update, Delete), paging, sorting, and searching in an ASP.NET MVC application. We'll walk through each step with detailed explanations and provide code snippets to ensure a clear understanding.
Step 1: Setting Up the ASP.NET MVC Application: Begin by creating a new ASP.NET MVC project in Visual Studio. Choose the appropriate template and configure the project settings as needed.
Step 2: Creating the Model: Define the model that represents the data entity for which you want to perform CRUD operations. For example, let's create a Product
model with properties such as Id
, Name
, Price
, etc.
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Step 3: Implementing CRUD Operations: Create controller actions to handle CRUD operations for the Product
model. These actions will interact with the data repository to perform database operations.
public class ProductController : Controller
{
private readonly IProductRepository _productRepository;
public ProductController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
// GET: /Product/Index
public ActionResult Index()
{
var products = _productRepository.GetAll();
return View(products);
}
// GET: /Product/Create
public ActionResult Create()
{
return View();
}
// POST: /Product/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
_productRepository.Add(product);
return RedirectToAction("Index");
}
return View(product);
}
// GET: /Product/Edit/1
public ActionResult Edit(int id)
{
var product = _productRepository.GetById(id);
return View(product);
}
// POST: /Product/Edit/1
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
_productRepository.Update(product);
return RedirectToAction("Index");
}
return View(product);
}
// GET: /Product/Delete/1
public ActionResult Delete(int id)
{
var product = _productRepository.GetById(id);
return View(product);
}
// POST: /Product/Delete/1
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
_productRepository.Delete(id);
return RedirectToAction("Index");
}
}
Step 4: Implementing Paging, Sorting, and Searching: To implement paging, sorting, and searching functionality, you can use features provided by ASP.NET MVC or third-party libraries like DataTables or PagedList.
Paging: Implement paging by dividing the data into smaller chunks and displaying them on different pages.
Sorting: Allow users to sort the data based on specific columns.
Searching: Provide a search functionality to filter data based on user-defined criteria.
Step 5: Integrating with Views: Create views to render the user interface for each controller action. Ensure that the views include elements for displaying data, performing CRUD operations, and implementing paging, sorting, and searching features.
let's add paging, sorting, and searching functionality to our ASP.NET MVC application. We'll provide code snippets for each feature.
Step 1: Implement Paging: You can use the
PagedList.Mvc
library to implement paging in your ASP.NET MVC application. First, install the library via NuGet:
Install-Package PagedList.Mvc
Then, in your controller action where you retrieve data, use the ToPagedList
method to paginate the results:
public ActionResult Index(int? page)
{
var pageNumber = page ?? 1;
var pageSize = 10; // Number of items per page
var products = _productRepository.GetAll().ToPagedList(pageNumber, pageSize);
return View(products);
}
In your view, render the paging links using the PagedListPager
HTML helper:
@using PagedList.Mvc
@model IPagedList<Product>
@{
ViewBag.Title = "Product List";
}
<!-- Display Product List Here -->
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }), PagedListRenderOptions.ClassicPlusFirstAndLast)
Step 2: Implement Sorting: You can implement sorting by allowing users to click on column headers to sort the data. Modify your controller action to handle sorting parameters:
public ActionResult Index(int? page, string sortOrder)
{
ViewBag.NameSortParam = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.PriceSortParam = sortOrder == "Price" ? "price_desc" : "Price";
var products = _productRepository.GetAll();
switch (sortOrder)
{
case "name_desc":
products = products.OrderByDescending(p => p.Name);
break;
case "Price":
products = products.OrderBy(p => p.Price);
break;
case "price_desc":
products = products.OrderByDescending(p => p.Price);
break;
default:
products = products.OrderBy(p => p.Name);
break;
}
var pageNumber = page ?? 1;
var pageSize = 10; // Number of items per page
var sortedProducts = products.ToPagedList(pageNumber, pageSize);
return View(sortedProducts);
}
In your view, add sorting links to column headers:
<th>
@Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParam })
</th>
<th>
@Html.ActionLink("Price", "Index", new { sortOrder = ViewBag.PriceSortParam })
</th>
Step 3: Implement Searching: You can implement searching by adding a search form to your view and modifying your controller action to filter results based on search criteria.
In your controller:
public ActionResult Index(int? page, string searchString)
{
var products = _productRepository.GetAll();
if (!String.IsNullOrEmpty(searchString))
{
products = products.Where(p => p.Name.Contains(searchString));
}
// Sorting logic here...
var pageNumber = page ?? 1;
var pageSize = 10; // Number of items per page
var searchedProducts = products.ToPagedList(pageNumber, pageSize);
return View(searchedProducts);
}
In your view, add a search form:
@using (Html.BeginForm("Index", "Product", FormMethod.Get))
{
<p>
Search by Name: @Html.TextBox("searchString")
<input type="submit" value="Search" />
</p>
}
Conclusion: By following the steps outlined in this guide, you can develop a robust ASP.NET MVC application that performs CRUD operations and includes features such as paging, sorting, and searching. ASP.NET MVC provides powerful tools and libraries to streamline the development process and create efficient and user-friendly web applications.