c# - Validation Rules and Business Rules in MVC -


i have mvc web project. according best practice, correct place add validation rules , business rules?

validation rules required fields , required formats.

business rules "this email taken in database"

here's how doing in register model:

public class registermodel : ivalidatableobject {     [display(name = "email address")]     [required(errormessage = "the email address required")]     [emailaddress(errormessage = "invalid email address")]     public string email { get; set; }      public ienumerable<validationresult> validate(validationcontext validationcontext)     {         var retval = new list<validationresult>();         using (var entity = new academicunitedatabaseentities())         {             if (entity.userprofiles.any(x => x.username == this.email))             {                 retval.add(new validationresult("email exist", new list<string> { "email" }));             }         }          return retval;     } } 

here's register controller:

    public actionresult register()     {         var model = new registermodel();         return this.view(model);     }      [httppost]     [validateantiforgerytoken]     public actionresult register(registermodel model)     {         if (!this.modelstate.isvalid)         {             return this.view(model);         }          model.createaccount();         return this.view("waitconfirmemail");     } 

why i'm doing way

  1. when check modelstate.isvalid in controller, have checked format of email , if exists in database. don't make calls database in controller, in model. (is best practice?)
  2. it binds "email exist" validation result email property can display validation results on view.

is best practice?

  1. is correct way add business rules in mvc?
  2. why or why not?
  3. if not best practice, can provide me of example of how register model best programmed checking business rules (if email exists)?

one alternative create custom validator attribute. solution, end big models. alternative create static helpers can plug in controller. there no right answer here, it's way you'd organize code. preference spread business logic across custom attributes can plug , play. way can refactor seamlessly.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -