Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

asp.net mvc - Conditional validation on model in MVC

I have a view & model that I use for both the edit and the insert page for a record. One of the business requirements is that a certain field is required on edit but not on new. Originally before this particular feature was added to the docket, i had the model like so:

[Required(ErrorMessage = "*")]
[Range(0.0, (double)decimal.MaxValue)]
[DisplayName("Cost")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public decimal ProposedCost { get; set; }

I would like to either remove the required property if it is an insert form, or add it if an edit form. What is the better approach? All my other validation is done like above. Or can I alter the model state? Thoughts?

EDIT

Something I should clarify is that they are still permitted to insert a cost on new, just not required.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're on MVC3/.NET4, you can use IValidatableObject which exists specifically for such purposes.

Quoting ScottGu,

...The IValidatableObject interface enables you to perform model-level validation, and enables you to provide validation error messages specific to the state of the overall model....

You model would look 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 be provided.");
        }
    }
}

and then in the controller,

[HttpPost]
public ActionResult Submit(MyViewModel model)
{
    if (!ModelState.IsValid) {
        //failed - report an error, redirect to action etc
    }
    //succeeded - save to database etc
}

Otherwise, the most clean solution would be to use view models - UpdateViewModel where the property is required, and CreateViewModel where it's not required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...