DEV Community

rahil merdiyev
rahil merdiyev

Posted on

Category Controller

Certainly! Here’s a blog-style explanation of your CategoryController class in ASP.NET Core MVC, which handles operations like creating, updating, deleting, and listing categories.

Building a Category Management System in ASP.NET Core MVC
In many web applications, managing categories for products or services is a common requirement. Whether you’re building an e-commerce site, a blog, or any content-driven platform, organizing your content into categories makes it easier to navigate and manage. In this blog post, we’ll walk through the CategoryController class, which handles the creation, update, deletion, and viewing of categories within an ASP.NET Core MVC application.

We will explore how to manage category data efficiently using Entity Framework Core, which allows us to interact with a database using LINQ queries, and we'll also see how to ensure proper validation and error handling along the way.

Overview of the Controller
This CategoryController class is responsible for managing the categories in the system. It allows us to:

Display a list of categories
Create new categories
Update existing categories
Delete categories
Let’s break down the code and see how each action is implemented.

The CategoryController Class
Here is the complete CategoryController class:

csharp
Copy
[Area("Manage")]
public class CategoryController : Controller
{
private readonly AppDbContext _context;

// Constructor to inject the AppDbContext to interact with the database
public CategoryController(AppDbContext context)
{
    _context = context;
}

// GET: Category/Index
public async Task<IActionResult> Index()
{
    var categories = await _context.Categories.Include(p => p.Products).ToListAsync();
    return View(categories);
}

// GET: Category/Create
public IActionResult Create()
{
    return View();
}

// POST: Category/Create
[HttpPost]
public IActionResult Create(Category category)
{
    if (!ModelState.IsValid)
    {
        return View(category); // Return the same view with validation errors
    }

    // Add the new category to the database
    _context.Categories.Add(category);
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}

// GET: Category/Delete/5
public IActionResult Delete(int? Id)
{
    if (Id == null)
    {
        return NotFound(); // Return a 404 if the Id is not provided
    }

    var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
    if (category == null)
    {
        return NotFound(); // Return a 404 if the category is not found
    }

    _context.Categories.Remove(category); // Remove the category from the database
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}

// GET: Category/Update/5
public IActionResult Update(int? Id)
{
    if (Id == null)
    {
        return NotFound(); // Return a 404 if the Id is not provided
    }

    var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
    if (category == null)
    {
        return NotFound(); // Return a 404 if the category is not found
    }

    return View(category); // Return the category to the view for editing
}

// POST: Category/Update/5
[HttpPost]
public IActionResult Update(Category newCategory)
{
    if (!ModelState.IsValid)
    {
        return View(newCategory); // Return the same view with validation errors
    }

    var oldCategory = _context.Categories.FirstOrDefault(p => p.Id == newCategory.Id);
    if (oldCategory == null)
    {
        return NotFound(); // Return a 404 if the category to be updated is not found
    }

    oldCategory.Name = newCategory.Name; // Update the category name with the new value
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}
Enter fullscreen mode Exit fullscreen mode

}
Breaking Down the Actions

  1. Index: Displaying a List of Categories The Index action is used to display all the categories in the system. We use Entity Framework Core's Include method to load related data — in this case, we’re also including any associated Products for each category.

csharp
Copy
public async Task Index()
{
var categories = await _context.Categories.Include(p => p.Products).ToListAsync();
return View(categories);
}
Include(p => p.Products): This eagerly loads the related Products for each category.
ToListAsync(): Executes the query asynchronously, returning a list of categories.
The categories are then passed to the view for display.

  1. Create: Adding a New Category The Create action is used for creating a new category. The action has two parts:

GET Action (Create): Displays the form for creating a new category.
POST Action (Create): Accepts the posted form data, validates it, and saves the new category to the database.
GET: Show the Create Form
csharp
Copy
public IActionResult Create()
{
return View();
}
This simply returns an empty form view.

POST: Handle the Form Submission
csharp
Copy
[HttpPost]
public IActionResult Create(Category category)
{
if (!ModelState.IsValid)
{
return View(category); // If the model is invalid, return the form with validation errors
}

_context.Categories.Add(category); // Add the new category to the database
_context.SaveChanges(); // Save the changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action to display the updated list of categories
Enter fullscreen mode Exit fullscreen mode

}
If the model is not valid (e.g., required fields are missing), we return the form view again, displaying validation errors.
If the model is valid, the category is added to the database, and changes are saved.

  1. Delete: Removing a Category The Delete action is responsible for removing a category from the system.

GET: Show Delete Confirmation
csharp
Copy
public IActionResult Delete(int? Id)
{
if (Id == null)
{
return NotFound(); // If the ID is null, return a 404
}

var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
if (category == null)
{
    return NotFound(); // If the category is not found, return a 404
}

_context.Categories.Remove(category); // Remove the category from the database
_context.SaveChanges(); // Save changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action to show the updated category list
Enter fullscreen mode Exit fullscreen mode

}
If the category is not found, it returns a 404 response.
If found, the category is removed from the database and changes are saved.

  1. Update: Editing a Category The Update action allows editing an existing category.

GET: Show the Update Form
csharp
Copy
public IActionResult Update(int? Id)
{
if (Id == null)
{
return NotFound(); // If the ID is null, return a 404
}

var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
if (category == null)
{
    return NotFound(); // If the category is not found, return a 404
}

return View(category); // Return the category data to the view for editing
Enter fullscreen mode Exit fullscreen mode

}
POST: Handle the Update Form Submission
csharp
Copy
[HttpPost]
public IActionResult Update(Category newCategory)
{
if (!ModelState.IsValid)
{
return View(newCategory); // Return the form with validation errors
}

var oldCategory = _context.Categories.FirstOrDefault(p => p.Id == newCategory.Id);
if (oldCategory == null)
{
    return NotFound(); // If the category is not found, return a 404
}

oldCategory.Name = newCategory.Name; // Update the category name
_context.SaveChanges(); // Save changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action
Enter fullscreen mode Exit fullscreen mode

}
Similar to the Create action, we validate the model, then update the existing category in the database.
Conclusion
In this post, we’ve built a simple but effective CategoryController in an ASP.NET Core MVC application, which handles the most common CRUD (Create, Read, Update, Delete) operations for categories. By using Entity Framework Core and model binding, we can easily interact with our database, validate data, and provide a responsive user experience.

This setup can be easily extended to include more complex features, such as category hierarchies, custom sorting, and pagination, depending on the requirements of your application.

Happy coding!

Certainly! Here’s a blog-style explanation of your CategoryController class in ASP.NET Core MVC, which handles operations like creating, updating, deleting, and listing categories.

Building a Category Management System in ASP.NET Core MVC
In many web applications, managing categories for products or services is a common requirement. Whether you’re building an e-commerce site, a blog, or any content-driven platform, organizing your content into categories makes it easier to navigate and manage. In this blog post, we’ll walk through the CategoryController class, which handles the creation, update, deletion, and viewing of categories within an ASP.NET Core MVC application.

We will explore how to manage category data efficiently using Entity Framework Core, which allows us to interact with a database using LINQ queries, and we'll also see how to ensure proper validation and error handling along the way.

Overview of the Controller
This CategoryController class is responsible for managing the categories in the system. It allows us to:

Display a list of categories
Create new categories
Update existing categories
Delete categories
Let’s break down the code and see how each action is implemented.

The CategoryController Class
Here is the complete CategoryController class:

csharp
Copy
[Area("Manage")]
public class CategoryController : Controller
{
private readonly AppDbContext _context;

// Constructor to inject the AppDbContext to interact with the database
public CategoryController(AppDbContext context)
{
    _context = context;
}

// GET: Category/Index
public async Task<IActionResult> Index()
{
    var categories = await _context.Categories.Include(p => p.Products).ToListAsync();
    return View(categories);
}

// GET: Category/Create
public IActionResult Create()
{
    return View();
}

// POST: Category/Create
[HttpPost]
public IActionResult Create(Category category)
{
    if (!ModelState.IsValid)
    {
        return View(category); // Return the same view with validation errors
    }

    // Add the new category to the database
    _context.Categories.Add(category);
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}

// GET: Category/Delete/5
public IActionResult Delete(int? Id)
{
    if (Id == null)
    {
        return NotFound(); // Return a 404 if the Id is not provided
    }

    var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
    if (category == null)
    {
        return NotFound(); // Return a 404 if the category is not found
    }

    _context.Categories.Remove(category); // Remove the category from the database
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}

// GET: Category/Update/5
public IActionResult Update(int? Id)
{
    if (Id == null)
    {
        return NotFound(); // Return a 404 if the Id is not provided
    }

    var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
    if (category == null)
    {
        return NotFound(); // Return a 404 if the category is not found
    }

    return View(category); // Return the category to the view for editing
}

// POST: Category/Update/5
[HttpPost]
public IActionResult Update(Category newCategory)
{
    if (!ModelState.IsValid)
    {
        return View(newCategory); // Return the same view with validation errors
    }

    var oldCategory = _context.Categories.FirstOrDefault(p => p.Id == newCategory.Id);
    if (oldCategory == null)
    {
        return NotFound(); // Return a 404 if the category to be updated is not found
    }

    oldCategory.Name = newCategory.Name; // Update the category name with the new value
    _context.SaveChanges(); // Save changes to the database

    return RedirectToAction(nameof(Index)); // Redirect to the index action to display the updated category list
}
Enter fullscreen mode Exit fullscreen mode

}
Breaking Down the Actions

  1. Index: Displaying a List of Categories The Index action is used to display all the categories in the system. We use Entity Framework Core's Include method to load related data — in this case, we’re also including any associated Products for each category.

csharp
Copy
public async Task Index()
{
var categories = await _context.Categories.Include(p => p.Products).ToListAsync();
return View(categories);
}
Include(p => p.Products): This eagerly loads the related Products for each category.
ToListAsync(): Executes the query asynchronously, returning a list of categories.
The categories are then passed to the view for display.

  1. Create: Adding a New Category The Create action is used for creating a new category. The action has two parts:

GET Action (Create): Displays the form for creating a new category.
POST Action (Create): Accepts the posted form data, validates it, and saves the new category to the database.
GET: Show the Create Form
csharp
Copy
public IActionResult Create()
{
return View();
}
This simply returns an empty form view.

POST: Handle the Form Submission
csharp
Copy
[HttpPost]
public IActionResult Create(Category category)
{
if (!ModelState.IsValid)
{
return View(category); // If the model is invalid, return the form with validation errors
}

_context.Categories.Add(category); // Add the new category to the database
_context.SaveChanges(); // Save the changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action to display the updated list of categories
Enter fullscreen mode Exit fullscreen mode

}
If the model is not valid (e.g., required fields are missing), we return the form view again, displaying validation errors.
If the model is valid, the category is added to the database, and changes are saved.

  1. Delete: Removing a Category The Delete action is responsible for removing a category from the system.

GET: Show Delete Confirmation
csharp
Copy
public IActionResult Delete(int? Id)
{
if (Id == null)
{
return NotFound(); // If the ID is null, return a 404
}

var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
if (category == null)
{
    return NotFound(); // If the category is not found, return a 404
}

_context.Categories.Remove(category); // Remove the category from the database
_context.SaveChanges(); // Save changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action to show the updated category list
Enter fullscreen mode Exit fullscreen mode

}
If the category is not found, it returns a 404 response.
If found, the category is removed from the database and changes are saved.

  1. Update: Editing a Category The Update action allows editing an existing category.

GET: Show the Update Form
csharp
Copy
public IActionResult Update(int? Id)
{
if (Id == null)
{
return NotFound(); // If the ID is null, return a 404
}

var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
if (category == null)
{
    return NotFound(); // If the category is not found, return a 404
}

return View(category); // Return the category data to the view for editing
Enter fullscreen mode Exit fullscreen mode

}
POST: Handle the Update Form Submission
csharp
Copy
[HttpPost]
public IActionResult Update(Category newCategory)
{
if (!ModelState.IsValid)
{
return View(newCategory); // Return the form with validation errors
}

var oldCategory = _context.Categories.FirstOrDefault(p => p.Id == newCategory.Id);
if (oldCategory == null)
{
    return NotFound(); // If the category is not found, return a 404
}

oldCategory.Name = newCategory.Name; // Update the category name
_context.SaveChanges(); // Save changes to the database

return RedirectToAction(nameof(Index)); // Redirect to the Index action
Enter fullscreen mode Exit fullscreen mode

}
Similar to the Create action, we validate the model, then update the existing category in the database.
Conclusion
In this post, we’ve built a simple but effective CategoryController in an ASP.NET Core MVC application, which handles the most common CRUD (Create, Read, Update, Delete) operations for categories. By using Entity Framework Core and model binding, we can easily interact with our database, validate data, and provide a responsive user experience.

This setup can be easily extended to include more complex features, such as category hierarchies, custom sorting, and pagination, depending on the requirements of your application.

Happy coding!

[Area("Manage")]
public class CategoryController : Controller
{
    AppDbContext _context;

    public CategoryController(AppDbContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index()
    {
        var categories = await _context.Categories.Include(p => p.Products).ToListAsync();
        return View(categories);
    }
    public IActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public IActionResult Create(Category category)
    {
        if (!ModelState.IsValid)
        {
            return View(category);
        }
        _context.Categories.Add(category);
        _context.SaveChanges();
        return RedirectToAction(nameof(Index));
    }
    public IActionResult Delete(int? Id)
    {
        if (Id == null) { return NotFound(); }
        var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
        if (category == null) { return NotFound(); }
        _context.Categories.Remove(category);
        _context.SaveChanges();
        return RedirectToAction(nameof(Index));
    }
    public IActionResult Update(int? Id)
    {
        if (Id == null) { return NotFound(); }
        var category = _context.Categories.FirstOrDefault(p => p.Id == Id);
        if (category == null) { return NotFound(); }
        return View(category);

    }
    [HttpPost]
    public IActionResult Update(Category newcategory)
    {
        if (!ModelState.IsValid) { return View(newcategory); }
        var oldcategory = _context.Categories.FirstOrDefault(p => p.Id == newcategory.Id);
        if (oldcategory == null) { return NotFound(); }
        oldcategory.Name = newcategory.Name;
        _context.SaveChanges();
        return RedirectToAction(nameof(Index));
    }


}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)