CarrierTypeController Documentation 🚚📦
File:
IrbyImaging/UI/Controllers/CarrierTypeController.cs
Assembly: IrbyImaging.UI
Author: kvamshi
Created: 03-31-2022
Last Modified: 05-17-2022
Table of Contents 📑
- Overview & Purpose
- Dependencies & Technologies
- Data Models & ViewModels
- API Endpoints Overview
- Key Functional Areas
- Error Handling & Return Types
- Third-Party Integrations
- UML Class Diagram
- Sample Code Blocks & Usage Examples
- Conclusion
1. Overview & Purpose 🎯
The CarrierTypeController is an ASP.NET Core MVC controller responsible for managing Carrier Types in the IrbyImaging application. It provides the following functionality:
- List all Carrier Types
- Create a new Carrier Type
- Edit an existing Carrier Type
This controller inherits from a BaseController to reuse common functionality (e.g., authentication, logging). It uses Entity Framework Core (IrbyContext) for data access and the HttpContextAccessor for retrieving user identity.
2. Dependencies & Technologies 🔧
| Dependency | Purpose |
|---|---|
| Microsoft.AspNetCore.Mvc | MVC Controller base classes & attributes |
| Microsoft.AspNetCore.Authorization | (Optionally) secure endpoints with policies/roles |
| Microsoft.EntityFrameworkCore | Database access via DbContext |
| Microsoft.AspNetCore.Http | Accessing HttpContext for user identity |
| Microsoft.Extensions.Configuration | Reading configuration values (e.g., connection strings) |
| IrbyImaging.DbContext | Contains IrbyContext (EF Core DbContext) |
| IrbyImaging.DomainClasses | Domain entities: CarrierType, CarrierTypeDetail |
3. Data Models & ViewModels 📊
3.1 CarrierType (Domain Model)
public class CarrierType
{
public Guid Id { get; set; }
public string Carrier { get; set; }
public bool IsInactive { get; set; }
public DateTime AddedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string AddedBy { get; set; }
public string ModifiedBy { get; set; }
// Used only for Index view to wrap details
public List<CarrierTypeDetail> CarriersTypeDetail { get; set; }
}
3.2 CarrierTypeDetail (ViewModel)
public class CarrierTypeDetail
{
public Guid Id { get; set; }
public string Carrier { get; set; }
public bool IsInactive { get; set; }
}
Note: The controller uses the
CarrierTypeentity itself to hold aList<CarrierTypeDetail>for the Index view. In a more layered design, a separate view model class would be preferable.
4. API Endpoints Overview 🌐
| HTTP Verb | Route | Action | Description |
|---|---|---|---|
| GET | /CarrierType |
Index() |
List all carrier types |
| GET | /CarrierType/Create |
Create() |
Show form to create a new carrier |
| POST | /CarrierType/Create |
Create(model) |
Process new carrier creation |
| GET | /CarrierType/Edit/{id} |
Edit(id) |
Show form to edit an existing carrier |
| POST | /CarrierType/Edit/{id} |
Edit(id, model) |
Process carrier update |
5. Key Functional Areas ⚙️
5.1 Index - List Carrier Types
-
Method Signature:
public async Task<IActionResult> Index() -
Workflow:
- Queries all
CarrierTypesordered byCarriername. - Maps each database entity to a
CarrierTypeDetail. - Wraps the collection in a
CarrierTypeview model. - Returns the Index view with populated model.
- Queries all
-
Code Snippet:
var atsContext = _context.CarrierTypes.OrderBy(a => a.Carrier); var carrierDetail = new CarrierType { CarriersTypeDetail = new List<CarrierTypeDetail>() }; foreach (var rec in atsContext) { carrierDetail.CarriersTypeDetail.Add(new CarrierTypeDetail { Id = rec.Id, Carrier = rec.Carrier, IsInactive = rec.IsInactive }); } return View(carrierDetail);
5.2 Create - Add New Carrier Type
5.2.1 GET: Display Create Form
-
Method Signature:
public IActionResult Create() -
Purpose:
Prepares a new emptyCarrierTypeand populates view data for any dropdowns (none required but scaffolded). -
Code Snippet:
var carrier = new CarrierType(); ViewData["Carrier"] = new SelectList(_context.CarrierTypes, "Id", "Carrier"); return View(carrier);
5.2.2 POST: Process Create Form
-
Method Signature:
[HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Carrier,IsInactive")] CarrierType carrierType) -
Workflow:
- Validate model state.
- Retrieve current user identity (defaults to
"System"if not authenticated). - Set audit fields:
Id = Guid.NewGuid()AddedDate,ModifiedDate= NowAddedBy,ModifiedBy= current userIsInactive= false
- Save to database and redirect to Index.
-
Code Snippet:
if (ModelState.IsValid) { var identityName = GetCurrentUserName() ?? "System"; carrierType.Id = Guid.NewGuid(); carrierType.AddedDate = carrierType.ModifiedDate = DateTime.Now; carrierType.AddedBy = carrierType.ModifiedBy = identityName; carrierType.IsInactive = false; _context.Add(carrierType); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); }
5.3 Edit - Modify Existing Carrier Type
5.3.1 GET: Display Edit Form
- Method Signature:
public async Task<IActionResult> Edit(int? id) - Workflow:
- Check
id != null, else return 404 NotFound. - Fetch entity via
_context.CarrierTypes.FindAsync(id). - If not found, return 404.
- Populate ViewData and return view.
- Check
5.3.2 POST: Process Edit Form
-
Method Signature:
[HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(Guid id, [Bind("Id,Carrier,IsInactive")] CarrierType carrierType) -
Workflow:
- Validate route
idmatchescarrierType.Id. - If model state is valid:
- Update
ModifiedDate,ModifiedBy. - Call
_context.Update(...)and_context.SaveChangesAsync().
- Update
- Handle
DbUpdateConcurrencyExceptionin case of concurrent edits. - Redirect to Index.
- Validate route
-
Code Snippet:
if (id != carrierType.Id) return NotFound(); if (ModelState.IsValid) { try { carrierType.ModifiedDate = DateTime.Now; carrierType.ModifiedBy = GetCurrentUserName() ?? "System"; _context.Update(carrierType); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CarrierTypeExists(carrierType.Id)) return NotFound(); throw; } return RedirectToAction(nameof(Index)); }
5.4 Utility Methods
| Method | Purpose |
|---|---|
private bool CarrierTypeExists(Guid id) |
Checks existence of a CarrierType by Id in the database. |
private bool CarrierTypeExists(Guid id)
{
return _context.CarrierTypes.Any(e => e.Id == id);
}
6. Error Handling & Return Types 🛡️
- 404 NotFound(): Returned when an expected record is missing.
- RedirectToAction(nameof(Index)): On successful Create or Edit, redirects back to Index.
- ModelState Checks: Ensures invalid input returns back to the form view with validation messages.
- DbUpdateConcurrencyException: Catches EF Core concurrency violations; rethrows if record still exists.
7. Third-Party Integrations 🔌
- Entity Framework Core: Core ORM for data persistence.
- Microsoft Identity (via HttpContextAccessor): Retrieves current user claims for audit tracking.
8. UML Class Diagram 🏗️
classDiagram
class BaseController {
<<abstract>>
- IrbyContext _context
- IConfiguration _configuration
+ BaseController(IrbyContext, IConfiguration)
}
class CarrierTypeController {
- IrbyContext _context
- IHttpContextAccessor _httpContextAccessor
- IConfiguration _configuration
+ Index() IActionResult
+ Create() IActionResult
+ Create(CarrierType) IActionResult
+ Edit(int?) IActionResult
+ Edit(Guid, CarrierType) IActionResult
- CarrierTypeExists(Guid) bool
}
class CarrierType {
+ Guid Id
+ string Carrier
+ bool IsInactive
+ DateTime AddedDate
+ DateTime ModifiedDate
+ string AddedBy
+ string ModifiedBy
+ List~CarrierTypeDetail~ CarriersTypeDetail
}
class CarrierTypeDetail {
+ Guid Id
+ string Carrier
+ bool IsInactive
}
BaseController <|-- CarrierTypeController
CarrierTypeController --> CarrierType
CarrierType --> CarrierTypeDetail
9. Sample Code Blocks & Usage Examples 💡
9.1 Navigating the UI
-
List Carrier Types
Browse tohttps://<host>/CarrierTypeto see a table of all carrier types. -
Add New Carrier Type
- Click Create New.
- Fill in the Carrier name.
- Submit to add.
-
Edit an Existing Carrier Type
- From the Index, click Edit next to a carrier.
- Modify the name or toggle Inactive.
- Submit to save changes.
9.2 AJAX Example (Optional)
// Example: fetch carriers via AJAX (if JSON endpoint existed)
fetch('/CarrierType/GetAll')
.then(res => res.json())
.then(data => console.log('Carrier Types:', data));
Note: The current controller serves Razor views. For SPA or API-based use, consider adding JSON-returning endpoints.
10. Conclusion 🏁
The CarrierTypeController is a straightforward ASP.NET Core MVC controller that encapsulates CRUD operations for CarrierType entities. It demonstrates:
- Use of EF Core for data access
- Model binding and validation for form posts
- Audit trail via
HttpContextAccessorand timestamp fields - Basic error handling with 404 responses and concurrency checks
By following this pattern, you can extend similar controllers for other domain entities (e.g., AssetModels, Departments) with minimal boilerplate. 🎉
End of Documentation