asp.net mvc - Conditional validation on model in MVC -
i have view & model use both edit , insert page record. 1 of business requirements field required on edit not on new. before particular feature added docket, had model so:
[required(errormessage = "*")] [range(0.0, (double)decimal.maxvalue)] [displayname("cost")] [displayformat(dataformatstring = "{0:d}", applyformatineditmode = true)] public decimal proposedcost { get; set; }
i either remove required property if insert form, or add if edit form. better approach? other validation done above. or can alter model state? thoughts?
edit
something should clarify still permitted insert cost on new, not required.
if you're on mvc3/.net4, can use ivalidatableobject
exists such purposes.
quoting scottgu,
...the ivalidatableobject interface enables perform model-level validation, , enables provide validation error messages specific state of overall model....
you model like
public class myviewmodel : ivalidatableobject { public long? id { get; set; } public decimal? proposedcost { get; set; } public ienumerable<validationresult> validate(validationcontext validationcontext) { if (id != null && proposedcost == 0) { yield return new validationresult("proposedcost must provided."); } } }
and in controller,
[httppost] public actionresult submit(myviewmodel model) { if (!modelstate.isvalid) { //failed - report error, redirect action etc } //succeeded - save database etc }
otherwise, clean solution use view models - updateviewmodel
property required, , createviewmodel
it's not required.
Comments
Post a Comment