IncidentViewModel.cs 📄

Assembly: IrbyImaging.UI
Author: kvamshi
Created On: 05‑17‑2022
Last Modified: 05‑17‑2022


Table of Contents

  1. Overview & Purpose 🎯
  2. Dependencies & Technologies 🛠️
  3. Key Functional Areas 🔑
  4. Class Diagram UML 📊
  5. ViewModel Properties Breakdown 📝
  6. Validation & Display Attributes ✅
  7. Usage in Controllers & Views ⚙️
  8. Sample Code Blocks 📌
  9. Usage Examples 📺
  10. Conclusion & Next Steps 🚀

1. Overview & Purpose 🎯

The IncidentViewModel is a data‐transfer object (DTO) used in the MVC/UI layer of the IrbyImaging application. It encapsulates all information needed to create, display, and edit an incident/ticket in the help‑desk system. This ViewModel:

  • Collects user input (form fields) with validation.
  • Provides dropdown/select lists and prepopulated options.
  • Carries file uploads (images) for incident attachments.
  • Contains metadata (status, timestamps, creator/updater).

It sits under the IrbyImaging.ViewModels namespace and is typically passed between Controllers and Razor Views.


2. Dependencies & Technologies 🛠️

Namespace Purpose
IrbyImaging.Utility Defines TicketType & TicketStatus enums.
Microsoft.AspNetCore.Http For IFormFile (file uploads).
Microsoft.AspNetCore.Mvc MVC attributes (HiddenInput).
Microsoft.AspNetCore.Mvc.Rendering SelectList for dropdowns.
System / System.Collections.Generic Core types (e.g., Guid, ICollection<>).
System.ComponentModel.DataAnnotations Data validation/display attributes.

Technologies:

  • ASP.NET Core MVC
  • Razor Views
  • Data Annotations for validation
  • SelectList for list bindings

3. Key Functional Areas 🔑

  1. Identification
    Unique ticket keys: Id, TicketNumber, TicketId.
  2. Customer Details
    Who reported the issue: name, username, email.
  3. Job Information
    Job number, title, department, employee #, callback.
  4. Issue Description
    Main & other descriptions; categorization lists.
  5. Requests & Options
    Hardware, software, enterprise, and shared‑access requests.
  6. Location & Shipping
    Street/shipping address, city, state, zip.
  7. Attachment Support
    File upload (IFormFile) and binary image content.
  8. Metadata
    Audit fields: created/updated by/on, status, type.
  9. Dropdown Data
    SelectList properties to populate <select> in views.

4. Class Diagram UML 📊

classDiagram
    class IncidentViewModel {
        + Guid Id
        + int TicketNumber
        + string TicketId
        + string CustomerName
        + string CustomerUsername
        + string ResponseEmail
        + string JobNumber
        + string JobTitle
        + string JobDepartment
        + string EmployeeNumber
        + string CallBackNumber
        + string Description
        + ICollection~RequestOptionForDetailsViewModel~ HardwareRequests
        + ICollection~RequestOptionForDetailsViewModel~ SoftwareRequests
        + ICollection~RequestOptionForDetailsViewModel~ EnterpriseRequests
        + ICollection~RequestOptionForDetailsViewModel~ AccessRequests
        + ICollection~RequestOptionForCreateViewModel~ HardwareOptions
        + ICollection~RequestOptionForCreateViewModel~ SoftwareOptions
        + ICollection~RequestOptionForCreateViewModel~ EnterpriseOptions
        + ICollection~RequestOptionForCreateViewModel~ AccessOptions
        + string OtherDescription
        + string StreetAddress
        + string ShippingAddress
        + string RequestedJson
        + bool IsNewEmployee
        + TicketType Type
        + string City
        + string State
        + DateTime CreatedOn
        + string CreatedBy
        + SelectList CustomerList
        + SelectList IssueList
        + IFormFile File
        + byte[] ImageContents
        + TicketStatus Status
        + string Zip
        + DateTime UpdatedOn
        + string UpdatedBy
    }

5. ViewModel Properties Breakdown 📝

5.1 Identification 🆔

Property Type Description
Id Guid Unique identifier.
TicketNumber int Numeric ticket reference.
TicketId string Human‐readable ticket code.

5.2 Customer Information 👤

Property Type Display / Validation
CustomerName string Who has the issue? (Required, HiddenInput)
CustomerUsername string (Required)
ResponseEmail string Response Email (Required, EmailAddress)

5.3 Job Details 💼

Property Type Display / Validation
JobNumber string Job Number (Required)
JobTitle string Job Title (Required)
JobDepartment string Job Department (Required)
EmployeeNumber string Employee Number
CallBackNumber string Callback Number (Required)

5.4 Issue & Descriptions 📝

Property Type Display / Validation
Description string Issue (Required)
OtherDescription string Please describe the issue (Required)

5.5 Request Collections 📋

(Selected request options in a details view.)

Property Type Display
HardwareRequests ICollection Hardware Request
SoftwareRequests ICollection Software Request
EnterpriseRequests ICollection Enterprise Request
AccessRequests ICollection Shared Access Request

5.6 Options for Creation ⚙️

(Checkbox lists in a create/edit form.)

Property Type Display
HardwareOptions ICollection Hardware Options
SoftwareOptions ICollection Software Options
EnterpriseOptions ICollection Enterprise Applications
AccessOptions ICollection Shared Access Options

5.7 Location & Shipping 📦

Property Type Display
StreetAddress string Shipping Address
ShippingAddress string Shipping Address
City string —
State string —
Zip string —

5.8 File Upload & Images 📷

Property Type Description
File IFormFile Uploaded file (e.g., screenshot).
ImageContents byte[] Binary contents of the file.

5.9 Metadata & Hidden Fields 🗂️

Property Type Attributes / Usage
RequestedJson string HiddenInput; holds serialized JSON payload.
IsNewEmployee bool HiddenInput; flags new employee tickets.
Type TicketType Enum: Incident, Request, etc.
Status TicketStatus Enum: Open, Closed, InProgress, etc.
CreatedOn DateTime Timestamp of creation.
CreatedBy string Username/ID of creator.
UpdatedOn DateTime Timestamp of last update.
UpdatedBy string Username/ID of updater.

5.10 Select Lists 🔽

Property Type Purpose
CustomerList SelectList Populate customer <select> control.
IssueList SelectList Populate issue‑type dropdown.

6. Validation & Display Attributes ✅

  • [Required]: Ensures the field is not null or empty.
  • [Display(Name = "...")]: Customizes label text in Razor views.
  • [EmailAddress]: Validates proper email format.
  • [HiddenInput]: Renders the field as a hidden <input> in forms.

These attributes drive both client‑side and server‑side validation in ASP.NET Core MVC.


7. Usage in Controllers & Views ⚙️

In a Controller

public class IncidentController : Controller
{
    // GET: Display blank create form
    public IActionResult Create()
    {
        var vm = new IncidentViewModel
        {
            CustomerList = new SelectList(_customerService.GetAll(), "Username", "Name"),
            IssueList    = new SelectList(Enum.GetValues(typeof(TicketType))),
            HardwareOptions   = _optionService.GetHardwareOptions(),
            SoftwareOptions   = _optionService.GetSoftwareOptions(),
            EnterpriseOptions = _optionService.GetEnterpriseOptions(),
            AccessOptions     = _optionService.GetAccessOptions(),
            CreatedOn = DateTime.UtcNow,
            CreatedBy = User.Identity.Name
        };
        return View(vm);
    }

    // POST: Process form submission
    [HttpPost]
    public IActionResult Create(IncidentViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // Re‑populate dropdowns/options on error
            model.CustomerList = new SelectList(_customerService.GetAll(), "Username", "Name");
            model.IssueList    = new SelectList(Enum.GetValues(typeof(TicketType)));
            return View(model);
        }

        // Map to domain/entity and save
        var incident = _mapper.Map<Incident>(model);
        _incidentService.Create(incident, model.File);
        return RedirectToAction(nameof(Details), new { id = incident.Id });
    }
}

In a Razor View (Create.cshtml)

@model IrbyImaging.ViewModels.IncidentViewModel

<form asp-action="Create" method="post" enctype="multipart/form-data">
  <div class="form-group">
    @Html.LabelFor(m => m.CustomerName)
    @Html.HiddenFor(m => m.CustomerName)
    @Html.ValidationMessageFor(m => m.CustomerName)
  </div>
  <div class="form-group">
    @Html.LabelFor(m => m.JobNumber)
    @Html.TextBoxFor(m => m.JobNumber, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.JobNumber)
  </div>
  <!-- More fields... -->
  <div class="form-group">
    @Html.LabelFor(m => m.File, "Attach Screenshot")
    <input asp-for="File" type="file" class="form-control" />
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

8. Sample Code Blocks 📌

Mapping ViewModel to Entity

public class IncidentProfile : Profile
{
    public IncidentProfile()
    {
        CreateMap<IncidentViewModel, Incident>()
            .ForMember(dest => dest.ImageData, opt => 
                opt.MapFrom(src => src.ImageContents))
            .ForMember(dest => dest.RequestOptions, opt =>
                opt.MapFrom(src => src.HardwareRequests
                                   .Concat(src.SoftwareRequests)
                                   .Concat(src.EnterpriseRequests)
                                   .Concat(src.AccessRequests)));
    }
}

Handling File Upload

public async Task<byte[]> SaveFileAsync(IFormFile file)
{
    if (file == null || file.Length == 0) return null;
    using var ms = new MemoryStream();
    await file.CopyToAsync(ms);
    return ms.ToArray();
}

9. Usage Examples 📺

  1. Create a New Incident

    • Navigate to /Incident/Create
    • Fill in required fields (marked with *)
    • Select requests from checkboxes
    • Attach image/screenshot
    • Click Submit
  2. View Details

    • /Incident/Details/{id}
    • Displays all ViewModel fields in a read‑only format
    • Shows a gallery of selected requests & uploaded image
  3. Edit Existing Ticket

    • /Incident/Edit/{id}
    • Pre‑populates IncidentViewModel
    • Allows updates to description, requests, or file attachments

10. Conclusion & Next Steps 🚀

The IncidentViewModel is central to the ticketing UI in the IrbyImaging system. It unifies all data concerns—validation, display metadata, dropdown options, and file uploads—into one easy‐to‐use class.

Next Steps:

  • Implement additional custom validation (e.g., cross‐field rules).
  • Add client‐side scripts to dynamically show/hide sections (e.g., new employee flows).
  • Integrate third‐party file storage for large attachments (AWS S3, Azure Blob).
  • Extend with localization attributes for multi‑language support.

Happy coding! ✨