c# - ModelState validation checking multiple boolean property -
i have view model have multiple boolean properties, in controller have checking modelstate.isvalid
before proceeding service layer. want create modelstate.isvalid
homecoming false
if none of boolean property set true, there way create happen?
here sample class
public class role { public int id {get; set;} [required(errormessage = "please come in role name")] public string name {get; set;} public bool iscreator {get; set;} public bool iseditor {get; set;} public bool ispublisher {get; set;} }
i implement own validation method on model. model end looking this:
public class role : ivalidatableobject { public int id {get; set;} [required(errormessage = "please come in role name")] public string name {get; set;} public bool iscreator {get; set;} public bool iseditor {get; set;} public bool ispublisher {get; set;} public ienumerable<validationresult> validate(validationcontext validationcontext) { if (!this.iscreator && !this.iseditor && !this.ispublisher)) { yield homecoming new validationresult("you must creator, editor or publisher"); } } }
notice how model:
implementsivalidateableobject
has method named validate
returns type ienumerable<validationresult>
during model binding process method automatically called , if validation result returned modelstate
no longer valid. using familiar code in controller create sure don't take action unless custom conditions check out:
public class somecontroller { public actionresult someaction() { if (modelstate.isvalid) { //do stuff! } } }
c# asp.net-mvc viewmodel model-validation
No comments:
Post a Comment