πŸ“‹ RequestOptionsController Documentation


File: IrbyImaging/UI/Controllers/RequestOptionsController.cs
Assembly: IrbyImaging.UI
Author: kvamshi
Created: 05-17-2022
Last Modified: 05-17-2022


πŸš€ Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Key Functional Areas
  4. Controller Class Diagram (UML)
  5. API Endpoints Overview
  6. View Models & Data Models
  7. Helper Methods & Utilities
  8. Error Handling & Return Types
  9. Sample Code Blocks & Usage Examples
  10. Conclusion

1. Overview & Purpose

The RequestOptionsController is an ASP.NET Core MVC controller responsible for CRUD operations on RequestOption entities. It allows users (typically IT department staff) to:

  • πŸ” List all available request options
  • πŸ“‹ View details of a specific option
  • ✏️ Create a new option
  • ✏️ Edit existing options
  • πŸ—‘οΈ Delete unwanted options

Use Case: A system administrator or manager configures various service options (e.g., hardware requests, software license types) including costs and approval requirements.


2. Dependencies & Technologies

Technology / Package Purpose
Microsoft.AspNetCore.Mvc MVC controller base classes & attributes
Microsoft.EntityFrameworkCore ORM for database operations
Microsoft.Extensions.Configuration Access to appsettings.json configuration
Microsoft.AspNetCore.Mvc.Rendering Building SelectListItem for dropdowns
IrbyImaging.DomainClasses Domain models: RequestOption, Department
IrbyImaging.UI.Controllers.BaseController Shared logic for controllers

3. Key Functional Areas

  1. Index
    • Fetches and displays all RequestOption records, sorted by Type and Item.
  2. Details
    • Shows a single option’s data based on its Guid ID.
  3. Create (GET/POST)
    • GET: Renders an empty form.
    • POST: Validates & persists a new option, then redirects to Index.
  4. Edit (GET/POST)
    • GET: Loads an existing option and department list for editing.
    • POST: Applies updates and handles concurrency.
  5. Delete (GET/POST)
    • GET: Confirms deletion.
    • POST: Removes the option and redirects.

4. Controller Class Diagram (UML)

classDiagram
    BaseController <|-- RequestOptionsController
    RequestOptionsController : - IrbyContext _context
    RequestOptionsController : - IConfiguration _configuration
    RequestOptionsController : + RequestOptionsController(context, config)
    RequestOptionsController : + Task<IActionResult> Index()
    RequestOptionsController : + Task<IActionResult> Details(Guid? id)
    RequestOptionsController : + IActionResult Create()
    RequestOptionsController : + Task<IActionResult> Create(RequestOption requestOption)
    RequestOptionsController : + Task<IActionResult> Edit(Guid? id)
    RequestOptionsController : + Task<IActionResult> Edit(Guid id, RequestOption requestOption)
    RequestOptionsController : + Task<IActionResult> Delete(Guid? id)
    RequestOptionsController : + Task<IActionResult> DeleteConfirmed(Guid id)
    RequestOptionsController : - bool RequestOptionExists(Guid id)

5. API Endpoints Overview

Action Method HTTP Verb Route Description
Index GET /RequestOptions/ List all request options
Details GET /RequestOptions/Details/{id} Show details for a specific option
Create (Render Form) GET /RequestOptions/Create Display new-option creation form
Create (Submit Data) POST /RequestOptions/Create Validate & save new option
Edit (Render Form) GET /RequestOptions/Edit/{id} Display edit form for an option
Edit (Submit Data) POST /RequestOptions/Edit/{id} Validate & update existing option
Delete (Confirm) GET /RequestOptions/Delete/{id} Show deletion confirmation page
Delete (Execute Delete) POST /RequestOptions/Delete/{id} Remove the option from the database

6. View Models & Data Models

RequestOption (Domain Model)

public class RequestOption
{
    public Guid Id { get; set; }
    public string Type { get; set; }            // e.g., "Hardware", "Software"
    public string Item { get; set; }            // e.g., "Laptop", "Antivirus"
    public decimal Cost { get; set; }           // e.g., 1200.00
    public bool ApprovalRequired { get; set; }  // true/false
    public string ApprovalDepartment { get; set; } // e.g., "IT Security"
}

Department (Domain Model)

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }         // e.g., "IT", "HR"
    public bool? IsDeleted { get; set; }     // Soft-delete flag
}

Note: In Create and Edit views, a dropdown of active departments is built using SelectListItem.


7. Helper Methods & Utilities

  • RequestOptionExists(Guid id)
    Private method to verify existence of an option before updating or deleting.

    private bool RequestOptionExists(Guid id)
    {
        return _context.Options.Any(e => e.Id == id);
    }
    
  • ViewBag.Departments
    Dynamically populated with non-deleted departments for <select> input:

    var departments = _context.Departments
                      .Where(d => d.IsDeleted != true)
                      .OrderBy(d => d.Name)
                      .ToList();
    
    ViewBag.Departments = departments
                          .Select(d => new SelectListItem {
                              Text = d.Name,
                              Value = d.Name
                          }).ToList();
    

8. Error Handling & Return Types

  • Null/Not Found
    Every action that takes a Guid? id checks for null or non-existent IDs:
    if (id == null) return NotFound();
    
  • Model Validation
    [ValidateAntiForgeryToken] + ModelState.IsValid guard POST endpoints.
  • Concurrency
    Edit POST wraps SaveChangesAsync() in try/catch for DbUpdateConcurrencyException, re-throws if unexpected:
    catch (DbUpdateConcurrencyException)
    {
        if (!RequestOptionExists(requestOption.Id))
            return NotFound();
        else
            throw;
    }
    

Return types for all actions are IActionResult, enabling:

  • View(model)
  • RedirectToAction(nameof(Index))
  • NotFound() for missing resources

9. Sample Code Blocks & Usage Examples

1. Fetching All Options (Index)

GET https://your-domain/RequestOptions
public async Task<IActionResult> Index()
{
    var list = await _context.Options
                     .OrderBy(o => o.Type)
                     .ThenBy(o => o.Item)
                     .ToListAsync();
    return View(list);
}

2. Creating a New Option

GET  /RequestOptions/Create   β†’ displays empty form
POST /RequestOptions/Create
  Content-Type: application/x-www-form-urlencoded

  Id=
  Type=Hardware
  Item=Monitor
  Cost=200.00
  ApprovalRequired=true
  ApprovalDepartment=IT

Controller Snippet:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind(...)] RequestOption requestOption)
{
    if (ModelState.IsValid)
    {
        requestOption.Id = Guid.NewGuid();
        _context.Add(requestOption);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    return View(requestOption);
}

3. Editing an Option

GET  /RequestOptions/Edit/{guid}
POST /RequestOptions/Edit/{guid}

10. Conclusion

The RequestOptionsController is a robust, standard ASP.NET Core MVC controller enabling full management of request options within the IrbyImaging application. It demonstrates:

  • Clean separation of concerns (Actions + Views + Models)
  • EF Core for data access with asynchronous patterns
  • Defensive programming via model validation and concurrency checks
  • Dynamic population of dropdowns using ViewBag

With this documentation, you should have a clear understanding of:

  • The flow of each CRUD operation
  • Dependencies required to run the controller
  • How to extend it (e.g., add authorization, logging, or new fields)

Happy coding! πŸŽ‰