views:

173

answers:

3

Hello. I'm developing a little site using ASP.NET MVC, MySQL and NHibernate.

I have a Contact class:

[ModelBinder(typeof(CondicaoBinder))]
public class Contact {
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual int Age { get; set; }    
}

And a Model Binder:

public class ContactBinder:IModelBinder {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
         Contact contact = new Contact ();
         HttpRequestBase form = controllerContext.HttpContext.Request;

         contact.Id = Int16.Parse(form["Id"]);
         contact.Name = form["Name"];
         contact.Age = Int16.Parse(form["Age"]);

         return contact;
    }
}

Also, I have a view with a form to update my database, using this action:

public ActionResult Edit([ModelBinder(typeof(ContactBinder))] Contact contact) {
    contactRepo.Update(contact);

    return RedirectToAction("Index", "Contacts");
}

Until here, everything is working fine. But I have to implement a form validation, before update my contact.

My question is: Where should I implement this validation? In ActionResult method or in Model Binder? Or anywhere else?

Thank you very much.

+2  A: 

Have a look at XVAL by Steve Sanderson.

Your business objects are where your business logic should be applied.

Kindness

Dan

XVal

Daniel Elliott
A: 

I second Steve Sanderson, his book is amazing.

I've really liked the nerd dinner approach written by Rob Conery, Scott Hanselman, Phil Haack, Scott Guthrie. Basically you have a method in each entity that validates against buisness logic. That method returns a list of RuleViolations that contain the field / error msg. You also expose a bool value for convience.

You get the free chapter here: Nerd Dinner Chapter

Chance
A: 

I think this case it is better follow Microsoft recommendation that is Validation with Service Layer

Cleiton