I refined the Controller I wrote here to make it so one could navigate to /Home/InvalidTest/ and pass an inappropriate Person object (in this case, a Person who lived to be 132 years old). ModelState.IsValid may be used to sanity check models on the C# side beyond what @Html.ValidationMessageFor may do in a View, and here I use it to catch the oddity of an 132-year-old Person.
using System;
using System.Web.Mvc;
using KeepFeelingValidation.Models;
namespace KeepFeelingValidation.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Person person = new Person();
person.Name = "Adolph Coors I";
person.AgeAtDeath = 82;
person.BirthDay = new DateTime(1847, 2, 4);
person.IsCrazy = true;
person.Id = Guid.NewGuid();
return View(person);
}
public ActionResult About(Person person)
{
if (ModelState.IsValid) return View();
return View("Invalid");
}
public ActionResult Invalid()
{
return View();
}
public ActionResult InvalidTest()
{
Person person = new Person();
person.Name = "Adolph Coors I";
person.AgeAtDeath = 132;
person.BirthDay = new DateTime(1847, 2, 4);
person.IsCrazy = true;
person.Id = Guid.NewGuid();
return RedirectToAction("About", "Home", person);
}
}
}
If I set a breakpoint at return View("Invalid"); and run the debugger, I can tell that a collection is attached to ModelState containing:
- metadata for each of the fields to validate
- and if the validations went less-than-lovely for each of the given fields
Yay!
No comments:
Post a Comment