Introduction
The Job Portal needs JobSeeker, JobListing, and Company entities — but you should not expose domain models directly to Razor. ViewModels shape data for each screen and carry validation rules.
After this article you will
- Distinguish domain models, view models, and DTOs
- Apply Data Annotations for validation
- Build Job Portal view models from scratch
- Validate models in controllers with ModelState
Prerequisites
- Article 8 — Layouts, Partial Views and View Components
- ShopNest.Web project from prior lessons
Concept deep-dive
| Type | Purpose | Example |
|---|---|---|
| Domain model | Database entity | JobListing with EF navigation props |
| ViewModel | One screen / form | JobApplyViewModel with resume upload |
| DTO | API boundary | JobListingDto without internal fields |
public class JobApplyViewModel
{
[Required][StringLength(100)]
public string FullName { get; set; }
[Required][EmailAddress]
public string Email { get; set; }
[Range(0, 50)]
public int YearsExperience { get; set; }
[Required]
public IFormFile Resume { get; set; }
}
In controller: if (!ModelState.IsValid) return View(model);. AutoMapper (Article 50) maps entity ↔ view model at scale.
Hands-on — ShopNest Job Portal
- Define entities: JobSeeker, Company, JobListing.
- Create JobSearchViewModel with filters (location, keyword, min salary).
- JobDetailsViewModel combines listing + company + apply form.
- Validate POST apply action; show field errors in view.
Common errors & best practices
- Over-posting: bind only safe properties — use view models, not entities, on forms.
- Missing [Required] on nullable value types — use Required or nullable reference types.
Interview questions
Q: Why not pass JobListing entity to view?
A: Over-posting, circular references, leaking internal fields; view models expose only what UI needs.
Q: Data Annotations vs FluentValidation?
A: Annotations on model; FluentValidation separate classes — better for complex rules (Article 39).
Summary
- Domain models map to DB; view models map to screens
- Data Annotations drive server validation
- Job Portal demonstrates search and apply view models
Previous: Layouts, Partial Views and View Components
Next: Forms, Model Binding and Validation
FAQ
Is ViewModel mandatory?
Strongly recommended for any non-trivial form or composite page.
Can one view model serve multiple views?
Possible but prefer focused view models per use case.