Partition Web Apps Intelligently: C#: Validate Objects with VAB: Listing 3

Microsoft's Microsoft Enterprise Library Validation Application Block (VAB) gives you a great way to validate business objects. This code shows you how to use the VBA to redisplay the page with error messages.

[AcceptVerbs(HttpVerb.Post)]
[ActionName(Actions.Create)]
public ActionResult Save(Contact contact)
{
    ValidationResults validationResults = Validation.
       Validate(contact);
    if (validationResults.IsValid)
    {
        contactManager.SaveContact(contact);
        return RedirectToAction(Actions.Index);
    }
    else
    {
        foreach (ValidationResult validationResult 
            in validationResults)
        {
            string mvcKey = GetMvcKey(validationResult);
            this.ViewData.ModelState.AddModelError(
                mvcKey, validationResult.Message);
        }
        IEnumerable<State> stateList = contactManager.
           GetStates();
        this.ViewData.Model = new 
            ContactViewData(contact, stateList);
        return View(Actions.Create);
    }
comments powered by Disqus
Most   Popular
Upcoming Events

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.