Skip to content

Instantly share code, notes, and snippets.

@stormwild
Created December 10, 2011 11:45
Show Gist options
  • Select an option

  • Save stormwild/1454973 to your computer and use it in GitHub Desktop.

Select an option

Save stormwild/1454973 to your computer and use it in GitHub Desktop.
To get a list of errors in the model state
[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
if (ModelState.IsValid)
{
repository.SaveModel(viewModel);
TempData["message"] = "Changes have been saved";
return RedirectToAction("Index");
}
else
{
// Referenced from http://stackoverflow.com/questions/5510814/c-sharp-net-mvc3-modelstate-isvalid - Darin Dimitrov
ViewBag.Errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
return View(viewModel);
}
}
@if (ViewBag.Errors != null)
{
foreach (var e in ViewBag.Errors)
{
<p>@e</p>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment