More Mvc Support - ModelState feedback

Developer
May 4, 2011 at 10:54 AM

Mvc has built in handling for a lot of stuff like making sure that required fields are filled out and that they match the expected length. I've just commited code that helps devs respond with Mvc results back to the grid.

Check out the renderers demo, FirstName and LastName must be between 5 and 30 chars, otherwise the commit fails. Use the toolbar buttons, they're the only ones that currently support this feaure.

Also try deleting the first person with the toolbar button, person 20 can't be deleted and there's a message stating as much.

From the Controller end, this is what you need to do for the edit;

private ActionResult AddOrEditPerson(Person person)
        {
            if (ModelState.IsValid == false)
            {
                return Json(GridResponse.Create(ModelState), JsonRequestBehavior.AllowGet);
            }

            Person other = _persons.SingleOrDefault(oth => oth.PersonId == person.PersonId);

            if (other == null)
            {
                other = new Person();
                other.PersonId = _persons.Max(per => per.PersonId) + 1;
                _persons.Add(other);
            }

            other.FirstName = person.FirstName;
            other.LastName = person.LastName;
            if (person.City.Id == Guid.Empty)
            {
                other.City = null;
            }
            else
            {
                other.City = _cities.Single(city => city.Id == person.City.Id);
            }

            return Json(GridResponse.Create(true), JsonRequestBehavior.AllowGet);
        }

And this for the update;

        public ActionResult DeletePerson(Person person)
        {
            if (person.PersonId == 20)
            {
                return Json(GridResponse.CreateFailure("This person can't be deleted, try another!"), JsonRequestBehavior.AllowGet);             
            }

            if (_persons.RemoveAll(oth => oth.PersonId == person.PersonId) == 1)
            {
                return Json(GridResponse.CreateSuccess(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(GridResponse.CreateFailure("Person not found!"), JsonRequestBehavior.AllowGet);             
            }
        }

Of course, you should wrap it all in a try catch that reports the error.