πŸ“¦ AssetModelsController Documentation


Table of Contents

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

Overview & Purpose

πŸš€ AssetModelsController is an ASP.NET Core MVC controller responsible for CRUD (Create, Read, Update, Delete) operations on Asset Models in the IrbyImaging application. It interacts with the IrbyContext (EF Core database context) and leverages ASP.NET Core MVC features:

  • List all asset models (Index)
  • Create new asset models (Create)
  • Edit existing asset models (Edit)

It extends the BaseController to inherit common behaviors (e.g., authentication, configuration settings).


Dependencies & Technologies

Technology / Library Purpose
ASP.NET Core MVC Web framework, routing, controllers, views
Entity Framework Core (EF) ORM, DB context, LINQ-to-Entities
Microsoft.Extensions.Configuration Configuration key/value injection
IrbyImaging.DomainClasses Domain models: AssetModel, AssetManufacturer, etc.
IrbyImaging.DbContext IrbyContext – EF Core database context
BaseController Common functionality for all controllers (logging, auth, config)

Controller Inheritance & Dependency Injection

public class AssetModelsController : BaseController
{
    private readonly IrbyContext _context;
    private readonly IConfiguration _configuration;

    public AssetModelsController(IrbyContext context, IConfiguration configuration)
        : base(context, configuration)
    {
        _context = context;
        _configuration = configuration;
    }
    // ... action methods
}
  • Inherits from BaseController
  • Injects
    • IrbyContext (EF Core DbContext)
    • IConfiguration (app settings)

Key Functional Areas (Actions)

1. Index

πŸ“ Signature

public async Task<IActionResult> Index()

Description

  • Fetches all AssetModel records from the database, including their related Make
  • Sorts by Make.Name, then by AssetModel.Name
  • Projects them into a view-model list (AssetModelDetail)
  • Returns the Index view with the combined model

Code Snippet

var atsContext = _context.AssetModels
    .Include(a => a.Make)
    .OrderBy(a => a.Make.Name)
    .ThenBy(a => a.Name);

var assetDetail = new AssetModel
{
    AssetsModelDetail = new List<AssetModelDetail>()
};

foreach (var rec in atsContext.ToList())
{
    assetDetail.AssetsModelDetail.Add(new AssetModelDetail
    {
        Id = rec.Id,
        MakeId = rec.MakeId,
        Make = rec.Make,
        Name = rec.Name,
        Category = rec.Category,
        Type = rec.Type,
        IsAvailableOption = rec.IsAvailableOption
    });
}

return View(assetDetail);

Return

  • View(assetDetail) β†’ renders Views/AssetModels/Index.cshtml

2. Create (GET)

πŸ“ Signature

public IActionResult Create()

Description

  • Prepares data for the Create form
  • Populates a dropdown list of Manufacturers (AssetManufacturers)

Code Snippet

ViewData["MakeId"] = new SelectList(
    _context.AssetManufacturers,
    "Id",
    "Name"
);
return View();

Return

  • View() β†’ renders Views/AssetModels/Create.cshtml

3. Create (POST)

πŸ“ Signature

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,MakeId,Name,Category,Type")] AssetModel assetModel)

Description

  1. Model Validation: checks ModelState.IsValid.
  2. Category Logic: if Category is not MobileDevice, null out Type.
  3. Default Flag: sets IsAvailableOption = true.
  4. Persistence: adds to _context, saves changes.
  5. Redirect: to Index on success; returns view with errors on failure.

Code Snippet

if (ModelState.IsValid)
{
    if (assetModel.Category != AssetCategory.MobileDevice)
        assetModel.Type = null;

    assetModel.IsAvailableOption = true;
    _context.Add(assetModel);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}

ViewData["MakeId"] = new SelectList(
    _context.AssetManufacturers, "Id", "Name", assetModel.MakeId
);
return View(assetModel);

Return

  • RedirectToAction(Index) or
  • View(assetModel) with validation messages

4. Edit (GET)

πŸ“ Signature

public async Task<IActionResult> Edit(int? id)

Description

  • Validates id parameter
  • Finds the AssetModel by id
  • Returns 404 NotFound() if missing
  • Populates manufacturer dropdown (ViewData["MakeId"])
  • Renders Edit view

Code Snippet

if (id == null) return NotFound();

var assetModel = await _context.AssetModels.FindAsync(id);
if (assetModel == null) return NotFound();

ViewData["MakeId"] = new SelectList(
    _context.AssetManufacturers, "Id", "Name", assetModel.MakeId
);
return View(assetModel);

Return

  • View(assetModel) or
  • NotFound()

5. Edit (POST)

πŸ“ Signature

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(
    int id,
    [Bind("Id,MakeId,Name,Category,Type,IsAvailableOption")] AssetModel assetModel
)

Description

  1. ID Check: if URL id β‰  assetModel.Id β†’ NotFound()
  2. ModelState validation
  3. Category Logic: same as Create
  4. Concurrency Handling: catches DbUpdateConcurrencyException to verify existence
  5. Redirect on success; re-display view on failure

Code Snippet

if (id != assetModel.Id) return NotFound();

if (ModelState.IsValid)
{
    try
    {
        if (assetModel.Category != AssetCategory.MobileDevice)
            assetModel.Type = null;

        _context.Update(assetModel);
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!AssetModelExists(assetModel.Id))
            return NotFound();
        else
            throw;
    }
    return RedirectToAction(nameof(Index));
}

ViewData["MakeId"] = new SelectList(
    _context.AssetManufacturers, "Id", "Name", assetModel.MakeId
);
return View(assetModel);

Return

  • RedirectToAction(Index) or
  • View(assetModel) or
  • NotFound()

6. AssetModelExists (Helper)

πŸ“ Signature

private bool AssetModelExists(int id)

Description

  • Simple exists check in the database
  • Used for concurrency exception handling

Code

return _context.AssetModels.Any(e => e.Id == id);

Return

  • true if exists, otherwise false

View Models & Data Models

Class Namespace Key Properties
AssetModel IrbyImaging.DomainClasses Id, MakeId, Make (nav), Name, Category, Type, IsAvailableOption
AssetModelDetail IrbyImaging.DomainClasses Id, MakeId, Make, Name, Category, Type, IsAvailableOption
AssetManufacturer IrbyImaging.DomainClasses Id, Name, ...

πŸ” Notes

  • The controller uses AssetModel itself as a β€œwrapper” to hold a List<AssetModelDetail> in the Index action.
  • AssetCategory and Type enumeration logic is defined in IrbyImaging.Utility.

Helper Methods & Utilities

  • BaseController (not shown) likely provides:

    • Authentication/Authorization
    • Logging
    • Common configuration reading
  • Model Binding

    • [Bind(...)] attribute restricts the posted properties to prevent over-posting.
  • SelectList

    • Populates dropdowns in the Razor views using ViewData["MakeId"].

Error Handling & Return Types

Scenario Handling Return Type
Missing id in Edit GET return NotFound(); 404 Not Found
Model validation fails (Create/Edit POST) Re-populate dropdown, return View 200 OK (Form View)
DB concurrency conflict on Edit POST Check existence β†’ NotFound() or throw 404 or exception
Successful Create/Edit RedirectToAction(nameof(Index)) 302 Redirect

API Endpoints Overview

HTTP Verb Route Action Description
GET /AssetModels Index List all asset models
GET /AssetModels/Create Create (GET) Show form to create a new asset model
POST /AssetModels/Create Create (POST) Persist new asset model
GET /AssetModels/Edit/{id} Edit (GET) Show form to edit existing asset model
POST /AssetModels/Edit/{id} Edit (POST) Persist changes to existing asset model

UML Class Diagram

+--------------------------------+
|     AssetModelsController      |
+--------------------------------+
| - _context: IrbyContext        |
| - _configuration: IConfiguration|
+--------------------------------+
| + Index(): Task<IActionResult> |
| + Create(): IActionResult      |
| + Create(AssetModel): Task<...>|
| + Edit(int?): Task<IActionResult>  |
| + Edit(int, AssetModel): Task<IActionResult> |
| - AssetModelExists(int): bool  |
+--------------------------------+

Usage Examples

1. List All Asset Models

GET https://yourserver.com/AssetModels
  • Response: HTML page listing all asset models, grouped by manufacturer.

2. Create New Asset Model

  1. Navigate to /AssetModels/Create
  2. Fill in Manufacturer, Name, Category, (optional) Type
  3. Submit β†’ POST /AssetModels/Create
POST /AssetModels/Create HTTP/1.1
Content-Type: application/x-www-form-urlencoded

MakeId=2&Name=UltraCam&Category=Camera&Type=

3. Edit Existing Asset Model

  1. Navigate to /AssetModels/Edit/5
  2. Modify fields
  3. Submit β†’ POST /AssetModels/Edit/5
POST /AssetModels/Edit/5 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

Id=5&MakeId=2&Name=UltraCamX&Category=Camera&Type=&IsAvailableOption=true

Conclusion

AssetModelsController provides a clean, MVC-oriented approach to manage AssetModel entities.
Key takeaways:

  • Uses EF Core for data access
  • Implements form-based CRUD with validation and concurrency checks
  • Leverages ViewData / SelectList to populate dropdowns
  • Ensures security via [ValidateAntiForgeryToken] and (optionally) [Authorize(Policy = "AdminPolicy")]

πŸš€ With these capabilities, you can efficiently list, create, and update asset models within the IrbyImaging application.