开发者

Is there automatic server side validation with asp.net mvc 3?

开发者 https://www.devze.com 2023-04-01 04:16 出处:网络
I have an asp.net mvc 3 application, and am now trying to add some validation to it. I am testing with a clean solution. I don\'t want the validation to occur on the client side (for now), so I have d

I have an asp.net mvc 3 application, and am now trying to add some validation to it. I am testing with a clean solution. I don't want the validation to occur on the client side (for now), so I have disabled this in Web.config:

<add key="ClientValidationEnabled" value="false"/>

I have a simple class which is implementing IValidatableObject, and I want to use the Validate function for the validation (not attributes).

public c开发者_开发知识库lass SomeClass : IValidatableObject
{
    public int Id { get; set; }
    public int LowNumber { get; set; }
    public int HighNumber { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (LowNumber > HighNumber)
        {
            yield return new ValidationResult("LowNumber should not be higher than HighNumber.");
        }
    }
}

Now to the question. Is server side validation applied automagically, and how? How do I disable this? I want to control this myself - saying something like this in my post action:

[HttpPost]
public string SomeAction(SomeClass model)
{
    if (TryValidateModel(model))
        return "All good";
    else
        return "No good"; 
}

Doing this makes the validation being called - and displayed - twice. Once for this call, and once from someone else. Who?


If you use validation attributes (or the IValidatableObject interface) then the server side validation will always be done when the model is bound using the model binder. If you wanted to override the server side validation I believe you would need to create your own model binder.

Some good information on the topic here and a great article on the binder and the validation pipeline here.


When you post to a controller action with a model as a parameter, ASP.NET MVC does some magic behind the scenes for you called model binding. The framework creates a new instance of the model and copies your form inputs to the model properties. During this process it will also fire data annotations validation for you and the IValidatableObject is part of data annotations.

So to answer your question the default ASP.NET MVC model binder is doing the validation. If you don't want this to happen, don't use data annotations attributes or implement IValidatableObject. Just create a custom function to handle the validation and call this function in your controller, though I'm not sure why you wouldn't want validation to happen automatically during model binding. Alternatively you could create a custom model binder that does not fire the validation.

0

精彩评论

暂无评论...
验证码 换一张
取 消