ASP.NET Core MVC Interview Question #13
What is a ViewModel in ASP.NET Core MVC?
MVC Fundamentals, Controllers, Views & Routing Junior Beginner
Quick Interview Answer
A ViewModel is a class designed specifically for the data and input needs of a view or UI workflow. It can combine values from multiple domain entities, contain display-specific properties, and expose only fields that the user is allowed to submit.
Detailed Explanation
A ViewModel is a class designed specifically for the data and input needs of a view or UI workflow. It can combine values from multiple domain entities, contain display-specific properties, and expose only fields that the user is allowed to submit.
Using ViewModels reduces coupling between the UI and persistence entities and helps prevent overposting. ViewModels can also carry validation attributes appropriate to the user interface.
Code Example
public class ProductEditViewModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
[Range(0.01, 1000000)]
public decimal Price { get; set; }
}