ASP.NET Core MVC Interview Question #195

How would you preserve user input when a POST validation fails?

Senior Practical MVC Scenarios & Production Architecture Senior Advanced

Quick Interview Answer

Return the same input model so MVC and Razor can redisplay attempted values and ModelState errors. Rebuild supporting data that is not posted by the form, such as dropdown options, lookup collections, or page-specific reference data.

Detailed Explanation

Return the same input model so MVC and Razor can redisplay attempted values and ModelState errors. Rebuild supporting data that is not posted by the form, such as dropdown options, lookup collections, or page-specific reference data.

Do not redirect after a validation failure because ModelState and the submitted form context would normally be lost. Redirect after a successful write using PRG.

Code Example

if (!ModelState.IsValid)
{
    model.Categories =
        await _lookup.GetCategoriesAsync(token);

    return View(model);
}

await _service.SaveAsync(model, token);
return RedirectToAction(nameof(Index));