ASP.NET Core MVC Intermediate

View models and mapping

A view model is a class shaped for one screen, separate from your database entities. This lesson shows why passing entities straight to views causes bugs and security holes, how to build view models for display and edit forms, and how to map between them.

Entity, view model, view
  1. StartDatabase entityProduct with every column and relation
  2. Step 2Select projectionOnly the fields this screen needs
  3. Step 3View modelProductListItem or ProductEditModel
  4. Step 4Razor viewStrongly typed to the view model
  5. EndPOST backBind the edit model; copy allowed fields

Why not use the entity directly

  • Over-posting: if an edit action binds a Product entity, an attacker can add IsAdmin=true or Price=1 to the form and the model binder will set it.
  • Screens rarely match tables: a product page needs the category name, review count and related items, not just Product columns.
  • Validation differs: a sign-up form has ConfirmPassword, which is not stored.
  • Loading whole entities when a list shows three columns wastes memory and database time.

A display view model

Project straight into the view model in the query, so the database returns only what the screen needs.

C#
public record ProductListItem(int Id, string Name, decimal Price, string Category, int Reviews);

public async Task<IActionResult> Index()
{
    var items = await db.Products
        .OrderBy(p => p.Name)
        .Select(p => new ProductListItem(p.Id, p.Name, p.Price, p.Category.Name, p.Reviews.Count))
        .ToListAsync();
    return View(items);
}

An edit view model

Bind only the fields the form may change, then copy them onto the entity. Anything else a user posts is ignored.

C#
public class ProductEditModel
{
    public int Id { get; set; }

    [Required, StringLength(200)]
    public string Name { get; set; } = "";

    [Range(0, 1_000_000)]
    public decimal Price { get; set; }

    public int CategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; } = [];
}

[HttpPost, ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ProductEditModel input)
{
    if (!ModelState.IsValid)
    {
        input.Categories = await CategoryOptions();
        return View(input);
    }
    var product = await db.Products.FindAsync(input.Id);
    if (product is null) return NotFound();

    product.Name = input.Name;          // only the allowed fields
    product.Price = input.Price;
    product.CategoryId = input.CategoryId;
    await db.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}

Mapping

Hand-written mapping, as above, is clear and fast, and the compiler finds mistakes. Select projections are the best way to map for reading. Mapping libraries can save typing on large models, but they hide what is copied, so many teams prefer plain code or source-generated mappers.

Interview question

What is over-posting and how do view models prevent it?

Over-posting happens when model binding fills properties the form never showed, because an attacker added extra fields such as IsAdmin or Price to the request. If the action binds an entity and saves it, those values are stored. A view model only has the properties the form should edit, and the action copies those onto the entity, so extra posted fields are ignored.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.