π¦ AssetModelsController Documentation
Table of Contents
- Overview & Purpose
- Dependencies & Technologies
- Controller Inheritance & Dependency Injection
- Key Functional Areas (Actions)
- View Models & Data Models
- Helper Methods & Utilities
- Error Handling & Return Types
- API Endpoints Overview
- UML Class Diagram
- Usage Examples
- 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
AssetModelrecords from the database, including their relatedMake - Sorts by
Make.Name, then byAssetModel.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
- Model Validation: checks
ModelState.IsValid. - Category Logic: if Category is not
MobileDevice, null outType. - Default Flag: sets
IsAvailableOption = true. - Persistence: adds to
_context, saves changes. - Redirect: to
Indexon 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)orView(assetModel)with validation messages
4. Edit (GET)
π Signature
public async Task<IActionResult> Edit(int? id)
Description
- Validates id parameter
- Finds the
AssetModelby 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)orNotFound()
5. Edit (POST)
π Signature
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(
int id,
[Bind("Id,MakeId,Name,Category,Type,IsAvailableOption")] AssetModel assetModel
)
Description
- ID Check: if URL
idβassetModel.IdβNotFound() - ModelState validation
- Category Logic: same as Create
- Concurrency Handling: catches
DbUpdateConcurrencyExceptionto verify existence - 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)orView(assetModel)orNotFound()
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
trueif exists, otherwisefalse
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
Indexaction. - 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"].
- Populates dropdowns in the Razor views using
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
- Navigate to
/AssetModels/Create - Fill in Manufacturer, Name, Category, (optional) Type
- 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
- Navigate to
/AssetModels/Edit/5 - Modify fields
- 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.