Where do you put your validation in asp.net mvc 3? -


one common recommended practice in asp.net mvc you should not send business models views.. instead should create viewmodels specific each view.

when done , call modelstate.isvalid method in controller checking validity of viewmodel not business object.

what conventional approach dealing this?

public class person { public int id {get; set;};  [required] public string name {get; set;}  [required] public string lastname {get; set;}  public virtual icollection<exam> exams {get; set;}  }  public class personformviewmodel {  public int id {get; set;};       [required] public string name {get; set;}  [required] public string lastname {get; set;}  } 

this have right im not sure if [required] attribute should appear on both models or viewmodel or business model.

any tips on issue appreciatedd.

more links support claim common practice use view models.

how add validation poco(template) classes

http://blogs.msdn.com/b/simonince/archive/2010/01/26/view-models-in-asp-net-mvc.aspx

my preference input validation on view models, , business validation on domain models.

in other words, data annotations such required fields, length validation, regex, etc should done on view models, , added model state when error occurs.

and you'll have business/domain rules rely on more "form", should either in domain models (execute validation after they're mapped back), or service layer.

all our models have method called "validate", call in services prior persisting. throw custom exceptions if fail business validation, gets caught controller , added model state.

may not everyone's cup of tea, it's consistent.

example of business validation, requested:

here's example of domain model have, represents generic "post" (question, photo, video, etc):

public abstract class post {    // .. fields, properties, domain logic, etc     public void validate()    {       if (!this.geospatialidentity.isvalidforthistypeofpost())          throw new domainexception(this, businessexception.postnotvalidforthisspatial.);    } } 

you see there, checking against business rules, , throwing custom exceptions. domainexception our base, , have many derived implementations. have enum called businessexception, contains values our exceptions. use extension methods on enum provide resource-based error message.

this not field on model im checking, e.g "all posts must have subject", because although part of domain, it's input validation first , foremost, , handled via data annotations on view model.

now, controller:

[httppost] public actionresult create(questionviewmodel viewmodel) {    if (!modelstate.isvalid)      return view(viewmodel);     try    {       // map viewmodel       var model = mapper.map<questionviewmodel,question>(viewmodel);        // save.       postservice.save(model); // generic save method, constraint: "where tpost: post, new()".        // commit.       unitofwork.commit();        // p-r-g       return redirecttoaction("index", new { id = model.postid });    }    catch (exception exc)     {       var typedexc = exc domainexception;        if (typedexc != null)       {          // internationalised, user-friendly domain exception, can show          modelstate.addmodelerror("error", typedexc.businesserror.todescription());       }       else       {           // anything, e.g database exception - show generic msg.          modelstate.addmodelerror("error", "sorry, error occured saving post. support has been notified. please try again later.");       }    }     return view(viewmodel); } 

so, time "save" method on service, model has passed input validation. save method calls post.validate(), invoking business rules.

if exception raised, controller catches , displays message. if gets pass save method , error occurs (90% of time, it's entity framework, example), show generic error message.

as said, not everyone, works our team. have clear seperation of presentation , domain validation, , consistent flow of control raw http post, redirect after success.

hth


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -