Asp.net MVC 3 Validation exclude some field validation in TryUpdateModel -


i using asp.net mvc razor , data annotation validators model:

public class person  {      public int id { get; set; }       [required]      public string firstname { get; set; }       [required]      public string lastname { get; set; }  }  

firstname , lastname requerd. want edit firstname. methode is:

public actionresult edit([bind(include = "firstname")]person person) {     var p = getperson();     if (tryupdatemodel(p))     {         //save changes;     } } 

but tryupdatemodel return false. because lastname invalid.

how can prevent check validation of lastname in tryupdatemodel?

note:

  • the code simplified. real code complex
  • i have use requierd 2 property
  • i dont want use different model class

i found nice solution. must remove unused field modelstate. modelstate.isvalid return true. first need create new attribute class:

public class validateonlyincomingvaluesattribute : actionfilterattribute {     public override void onactionexecuting(actionexecutingcontext filtercontext)     {         var modelstate = filtercontext.controller.viewdata.modelstate;         var valueprovider = filtercontext.controller.valueprovider;          var keyswithnoincomingvalue = modelstate.keys.where( x=>!valueprovider.containsprefix(x) );         foreach (var key in keyswithnoincomingvalue)             modelstate[key].errors.clear();     } } 

then add attribute on methode:

[validateonlyincomingvaluesattribute] public actionresult edit([bind(include = "firstname")]person person) {     var p = getperson();     if (modelstate.isvalid)     {         tryupdatemodel(p);         //save changes;     } } 

look @ this: http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -