开发者

ASP .NET MVC 3 - RemoteAttribute override IsValid, access to the additional fields

开发者 https://www.devze.com 2023-03-31 12:14 出处:网络
Folks, i am creating a new attribute which inhetirs from System.Web.Mvc.RemoteAttribute. I would like to override the method IsValid for that the validation also works without the enabled JavaScript.

Folks, i am creating a new attribute which inhetirs from System.Web.Mvc.RemoteAttribute. I would like to override the method IsValid for that the validation also works without the enabled JavaScript. But i don't know how i can acces to the additional fields. My code is:

[AttributeUsage(AttributeTargets.Property)]
public class DocumentationAttribute : System.Web.Mvc.RemoteAttribute
{
    public DocumentationAttribute()
        : base("ValidPass", "Validation")
    {
        base.HttpMethod = "Post";
    }
    private DocumentationAttribute(string routeName)
        : base(routeName)
    {

    }
    private DocumentationAttribute(string action, string controller)
        : base(action, controller)
    {

    }
    private DocumentationAttribute(string action, string controller, string areaName)
        : base(action, controller, areaName)
    {

    }

    public override bool IsValid(object value)
    {
        //How can i access to the additional fields?
    }}

Class Model:

        [Display(Name = "Passport")]
        [Documentation(ErrorMessage = "{0} not valid", AdditionalFields = "IDPass")]
        public virtual String Passport
        {
            s开发者_如何学运维et;
            get;
        }


You can't do remote validation without javascript. That's how it works. You might as well just rely on server-side validation only, because that's the only kind of validation that works without javascript.

Are you trying to create a validator that works remotely with javascript, but does serverside if javascript is disabled? If so, then you should create a custom attribute derived from ValidationAttribute, and use remote as well.

Specifically for your question, you need to create a public property in your attribute called AdditionalFields, this gets set in the initializer when you declare the property, then you can access the property from your IsValid.

EDIT:

Based on your additional information, you need to use the second form of IsValid that takes the validation context. You would do something like this:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    var fields = validationContext.ObjectType.GetProperty(this.AdditionalFields);
    var fieldsValue = (string)fields.GetValue(validationContext.ObjectInstance, null);
}
0

精彩评论

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