Set Validation error in ASP.Net MVC Controller

Every time I need to set a validation error in a controller, I need to look up how to do this. But it is very simple. So I’ll just write it down here, for future reference: In controller do:

ModelState.AddModelError("FieldName", "Error message for User");

If you leave FieldName blank, the error will come up in validation summary. In a view you’ll have to do this:

@Html.ValidationSummary(true) // for the whole model
@Html.ValidationMessageFor(m => m.UserName) // for individual model field