Skip to main content

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.

Comments

Popular posts from this blog

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...