📄 CreateViewModel.cs Documentation

Assembly: IrbyImaging.UI
Namespace: IrbyImaging.Models
Author: kvamshi
Created: 2022‑03‑31
Last Modified: 2022‑03‑31


📑 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. UML Class Diagram
  4. Key Functional Areas
  5. View Model Usage
  6. Sample Code Blocks & Examples
  7. Conclusion

🚀 Overview & Purpose

The CreateViewModel is an abstract view model designed to capture the common fields required when creating an asset in the IrbyImaging application. It centralizes:

  • 📋 Serial Number
  • 📌 Asset Status
  • 📅 Purchase Date
  • 🏷️ Make/Model Selection
  • 👤 Assigned User
  • 📝 Notes
  • ❗ Error Message

This base class can be inherited by more specialized creation view models (e.g., CameraCreateViewModel, PrinterCreateViewModel), ensuring consistency across different asset types.


🛠️ Dependencies & Technologies

Package / Namespace Purpose
Microsoft.AspNetCore.Mvc.Rendering SelectList, SelectListItem for dropdown data.
System.ComponentModel.DataAnnotations Property validation & display metadata.
IrbyImaging.Utility AssetStatus enum (defines asset lifecycle).

📊 UML Class Diagram

classDiagram
    abstract class CreateViewModel {
        <<abstract>>
        +string SerialNumber
        +AssetStatus Status
        +DateTimeOffset PurchaseDate
        +int ModelId
        +IEnumerable<SelectListItem> ModelList
        +Guid OwnerId
        +SelectList OwnerList
        +string Notes
        +string ErrorMessage
    }

🔑 Key Functional Areas

4.1 Core Properties

Property Type Description
SerialNumber string Serial number of the asset.
Status AssetStatus Current lifecycle state of asset.
PurchaseDate DateTimeOffset When the asset was purchased.
ModelId int FK to a Make/Model record.
ModelList IEnumerable<SelectListItem> Drop‑down options for models.
OwnerId Guid FK to an ApplicationUser (Assigned To).
OwnerList SelectList Drop‑down of users.
Notes string Optional freeform notes.
ErrorMessage string Used to propagate errors back to the view.

4.2 Data Annotations & Validation

  • [Display(Name = "...")]
    Provides user‑friendly labels in forms.

  • [DataType(DataType.Date)]
    Renders PurchaseDate as a date picker (no time part).

Tip: Additional attributes (e.g., [Required], [StringLength]) can be added in derived classes for asset‑specific validation.


4.3 Error Handling

  • ErrorMessage
    A simple string property to pass errors (e.g., validation or business logic failures) from your controller back to the view.
    • If non‑empty, you can render it prominently in the form.

🎨 View Model Usage

5.1 Populating Select Lists

Populate ModelList and OwnerList in your controller:

public async Task<IActionResult> Create()
{
    var vm = new CameraCreateViewModel()
    {
        ModelList = (await _modelService.GetAllAsync())
                        .Select(m => new SelectListItem(m.Name, m.Id.ToString())),
        OwnerList = new SelectList(await _userService.GetAllUsersAsync(), "Id", "FullName"),
        PurchaseDate = DateTimeOffset.Now
    };
    return View(vm);
}

5.2 Rendering in a Razor View

@model CameraCreateViewModel

<form asp-action="Create" method="post">
  <div class="form-group">
    <label asp-for="SerialNumber"></label>
    <input asp-for="SerialNumber" class="form-control" />
    <span asp-validation-for="SerialNumber" class="text-danger"></span>
  </div>

  <div class="form-group">
    <label asp-for="Status"></label>
    <select asp-for="Status" asp-items="Html.GetEnumSelectList<AssetStatus>()"
            class="form-control"></select>
  </div>

  <div class="form-group">
    <label asp-for="PurchaseDate"></label>
    <input asp-for="PurchaseDate" class="form-control" type="date" />
  </div>

  <div class="form-group">
    <label asp-for="ModelId"></label>
    <select asp-for="ModelId" asp-items="Model.ModelList" 
            class="form-control"></select>
  </div>

  <div class="form-group">
    <label asp-for="OwnerId"></label>
    <select asp-for="OwnerId" asp-items="Model.OwnerList" 
            class="form-control"></select>
  </div>

  <div class="form-group">
    <label asp-for="Notes"></label>
    <textarea asp-for="Notes" class="form-control"></textarea>
  </div>

  @if (!string.IsNullOrEmpty(Model.ErrorMessage))
  {
      <div class="alert alert-danger">
        <strong>Error:</strong> @Model.ErrorMessage
      </div>
  }

  <button type="submit" class="btn btn-primary">Create</button>
</form>

5.3 Controller Example

[HttpPost]
public async Task<IActionResult> Create(CameraCreateViewModel vm)
{
    if (!ModelState.IsValid)
    {
        // Re-populate dropdowns
        await PopulateListsAsync(vm);
        return View(vm);
    }

    var result = await _assetService.CreateCameraAsync(vm);
    if (!result.Success)
    {
        vm.ErrorMessage = result.ErrorMessage;
        await PopulateListsAsync(vm);
        return View(vm);
    }

    return RedirectToAction(nameof(Index));
}

🧩 Sample Code Blocks & Examples

  1. Derived ViewModel

    public class PrinterCreateViewModel : CreateViewModel
    {
        [Display(Name="Tray Capacity")]
        public int TrayCapacity { get; set; }
    
        // Additional printer-specific fields...
    }
    
  2. Service Method Signature

    public Task<ServiceResult> CreateCameraAsync(CameraCreateViewModel vm);
    
  3. Error Handling Pattern

    if (!result.Success)
    {
        vm.ErrorMessage = result.ErrorMessage;
        // ...
    }
    

✅ Conclusion

The CreateViewModel abstract class standardizes the user input required when creating new assets in the IrbyImaging application. By centralizing common fields, annotations, and error‑handling support, it:

  • Ensures consistency across all asset‑creation workflows
  • Simplifies controller logic and Razor views
  • Provides a clean base for extending asset‑specific creation models

🚀 With this foundation, you can quickly spin up new asset‑type forms by inheriting from CreateViewModel and adding only the fields unique to that type. Enjoy building!