validation - Controller.ValidateModel method. How it work? -
i have following model class:
public abstract class companyformviewmodelbase { public companyformviewmodelbase() { role = new companyrolelistviewmodel(); contactperson = new personlistviewmodel(); sector = new sectorlistviewmodel(); } [required] [display(name = "company name")] public string companyname { get; set; } public companyrolelistviewmodel role { get; set; } [display(name = "contact name")] public personlistviewmodel contactperson { get; set; } public sectorlistviewmodel sector { get; set; } } public class addcompanyviewmodel : companyformviewmodelbase, ivalidatableobject { public ienumerable<validationresult> validate(validationcontext validationcontext) { plugandabandonentities db = new plugandabandonentities(); companyname = companyname.trim(); var results = new list<validationresult>(); if (db.company.where(p => p.companyname.tolower() == companyname.tolower()).count() > 0) results.add(new validationresult("company exists.", new string[] { "companyname" })); return results; } }
it works fine "classic" using like:
[httppost] [validateantiforgerytoken] public actionresult create(plugandabandon.viewmodels.addcompanyviewmodel model) { if (modelstate.isvalid) { createcompany(model); return redirecttoaction("index"); } else { return view(model); } }
but want use model class another, ajax form also. have following method:
public jsonresult returnjsonaddingcompany(string companyname, int roleid, int sectorid, int personid) { plugandabandon.viewmodels.addcompanyviewmodel model = new viewmodels.addcompanyviewmodel() { companyname = companyname, contactperson = new viewmodels.personlistviewmodel() { selecteditem = personid }, role = new viewmodels.companyrolelistviewmodel() { selecteditem = roleid }, sector = new viewmodels.sectorlistviewmodel() { selecteditem = sectorid } }; validatemodel(model); if (modelstate.isvalid) { createcompany(model); } else { throw new exception("company such name exists"); } var list = utils.companylist(); return json(list, jsonrequestbehavior.allowget); }
look @
validatemodel(model);
line. if model correct - works fine. if not correct - throw exception , break continue executing of method (and return exception view). also, if set breakpoint on
public ienumerable<validationresult> validate(validationcontext validationcontext)
method, never called in invalid model case! (with valid model validate method called). want have behaviour "classic" method, validate model , validate modelstate.isvalid. behaviour of validatemodel(model) strange me, it's "black box"...
validatemodel()
throws exception if model not valid. instead, use tryvalidatemodel()
from documentation
the tryvalidatemodel() validatemodel() method except tryvalidatemodel() method not throw invalidoperationexceptionexception if model validation fails.
Comments
Post a Comment