суббота, 26 февраля 2011 г.

Remote validation in ASP.NET MVC 2 with jQuery

In my research for CQRS concept project I want to use ASP.NET DataAnnotations for automatically support validation for my view models, but I want to use in the same way validation rules on client side, in standard DataAnnotations it supports client code associations for standard attributes provided with ASP.NET script. Unfortunately, in current version of ASP.NET MVC 2 doesn't support remote validation using ajax call, in MvcContrib project we can take implementation, but it doesn't meet my requirements and during testing I find some cases where it completely even doesn't be called. Simple case was when we submit form, so we can't process validation result in JavaScript callback, because page have been already sent.
I create additional params, so right now we can control processing remote validation, using jQuery synchronous ability.
JavaScript validation function:
Sys.Mvc.ValidatorRegistry.validators.remote = function (rule) {
    var url = rule.ValidationParameters.url;
    var parameterName = rule.ValidationParameters.parameterName;
    var isAsync = rule.ValidationParameters.isAsync=='true' || false;
    var message = rule.ErrorMessage;
    var result = true;

    var onComplete = function (responseData) {
        var lowerData = responseData.toLowerCase();
        if (lowerData != 'true') {
            var newMessage = (lowerData == 'false' ? message : responseData);
            result = newMessage;
        }
    };

    return function (value, context) {
        if (!value || !value.length) {
            return true;
        }

        if (context.eventName == 'blur') {
            return true;
        }

        var ajaxCallParam = {
            url: url,
            async: isAsync,
            data: $.param([{ name: parameterName, value: value}])
        }

        if (isAsync) {
            ajaxCallParam.success = onComplete;
        }

        var responseData = $.ajax(ajaxCallParam);

        if (!isAsync) {
            onComplete(responseData.responseText);
        }

        return result;
    };
}; 
Where custom Remote validation attribute:
public sealed class RemoteValidationAttribute : ValidationAttribute
{
    public string Action { get; set; }
    public string Area { get; set; }
    public string Controller { get; set; }
    public string ParameterName { get; set; }
    public string RouteName { get; set; }

    public bool IsAsync { get; set; }


    public override bool IsValid(object value)
    {
        return true;
    }
} 
With actual Remote Validator:
public class RemoteValidator : DataAnnotationsModelValidator
{
    public RemoteValidator(ModelMetadata metadata, ControllerContext context,
                           RemoteValidationAttribute attribute) :
                               base(metadata, context, attribute)
    {
    }

    public override IEnumerable GetClientValidationRules()
    {
        var rule = new ModelClientValidationRule
                       {
                           ErrorMessage = ErrorMessage,
                           ValidationType = "remote"
                       };

        rule.ValidationParameters["url"] = GetUrl();
        rule.ValidationParameters["parameterName"] = Attribute.ParameterName;
        rule.ValidationParameters["isAsync"] = Attribute.IsAsync.ToString().ToLower();
        return new[] {rule};
    }

    private string GetUrl()
    {
        var rvd = new RouteValueDictionary
                                       {
                                           {"area", Attribute.Area ?? string.Empty },
                                           {"controller", Attribute.Controller},
                                           {"action", Attribute.Action}
                                       };

        var virtualPath = RouteTable.Routes.GetVirtualPath(ControllerContext.RequestContext,
                                                           Attribute.RouteName, rvd);
        if (virtualPath == null)
        {
            throw new InvalidOperationException("No route matched!");
        }

        return virtualPath.VirtualPath;
    }
}
That we have to register on application start up:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
    typeof(RemoteValidationAttribute),
    typeof(RemoteValidator)
    );

ASP.NET MVC 3 presented remote validation out of box, but previous implementation still need such type of functionality. My implementation based on original post by Brad Wilson.

Thank you, and I am always waiting for any feedback.

11 коммент.:

Анонимный комментирует...

Great job. Because i'm a newbie in this area this topic was the most useful for me.

jackbroobgm комментирует...

Verification and Validation are the activities performed to improve the quality and reliability of the system and assure the product satisfies the customer needs.
Verification assures the product of each development phase meets their respective requirements.
Validation assures the final product meets the client requirements.

software validation

Unknown комментирует...

I really like examining and also following ones write-up when i locate them incredibly beneficial and also fascinating.
That write-up is usually just as beneficial along with fascinating.Verification and Validation both are independent type of testing. Obviously,
If we look both of these activities as a whole, we can also call it testing.


software validation

Unknown комментирует...


This applies not only during the IQ, OQ and PQ validation phases, but far earlier,
beginning with the first meeting, and continuing through analysis of your process.
Software validation is a part of the design validation for a finished device,
but is not separately defined in the Quality System regulation.

software validation

Unknown комментирует...

Verification and Validation are the activities performed to improve the quality and reliability of the system and assure the product satisfies the customer needs.
Verification assures the product of each development phase meets their respective requirements.
Validation assures the final product meets the client requirements.

software validation

Unknown комментирует...

I also tell my team members to spend qaulity time doing analysis of the work they do. Do not spend the entire day in just doing testing.
Spending everyday sometime on Analysis will help them
to move in the right direction in the work and also helps them to see in a bigger and broader perspective of the work.
Finally, just spend good amount of time in planning, reviews and analysis, the execution will be done like in no time.

<a href="http://softwarevalidation.skyrock.com/3242076685-software-validation.html
>software validation</a>

Unknown комментирует...

Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog. Recently I did Software Testing Training in Chennai at a reputed training institutes. This is really useful for me to make a bright future in IT field.

mary Brown комментирует...

As I read the blog I felt a tug on the heartstrings. it exhibits how much effort has been put into this.
Final Year Project Domains for CSE

Spring Training in Chennai

Project Centers in Chennai for CSE

Spring Framework Corporate TRaining

İLSU SAYAN комментирует...

cami avizesi - no deposit bonus forex 2021 - takipçi satın al - takipçi satın al - takipçi satın al - takipcialdim.com/tiktok-takipci-satin-al/ - instagram beğeni satın al - instagram beğeni satın al - btcturk - tiktok izlenme satın al - sms onay - youtube izlenme satın al - no deposit bonus forex 2021 - tiktok jeton hilesi - tiktok beğeni satın al - binance - takipçi satın al - uc satın al - sms onay - sms onay - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - takipcialdim.com/instagram-begeni-satin-al/ - tiktok takipçi satın al - tiktok beğeni satın al - twitter takipçi satın al - trend topic satın al - youtube abone satın al - instagram beğeni satın al - perde modelleri - instagram takipçi satın al - takipçi satın al - instagram takipçi satın al - betboo

Unknown комментирует...

instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
instagram takipçi satın al
takipçi satın al
aşk kitapları
tiktok takipçi satın al
instagram beğeni satın al
youtube abone satın al
twitter takipçi satın al
tiktok beğeni satın al
tiktok izlenme satın al
twitter takipçi satın al
tiktok takipçi satın al
youtube abone satın al
tiktok beğeni satın al
instagram beğeni satın al
trend topic satın al
trend topic satın al
youtube abone satın al
beğeni satın al
tiktok izlenme satın al
sms onay
youtube izlenme satın al
tiktok beğeni satın al
sms onay
sms onay
perde modelleri
instagram takipçi satın al
takipçi satın al
tiktok jeton hilesi
pubg uc satın al
sultanbet
marsbahis
betboo
betboo
betboo

Unknown комментирует...

instagram takipçi satın al
ucuz takipçi
takipçi satın al
https://takipcikenti.com
https://ucsatinal.org
instagram takipçi satın al
https://perdemodelleri.org
https://yazanadam.com
instagram takipçi satın al
balon perdeler
petek üstü perde
mutfak tül modelleri
kısa perde modelleri
fon perde modelleri
tül perde modelleri
https://atakanmedya.com
https://fatihmedya.com
https://smmpaketleri.com
https://takipcialdim.com
https://yazanadam.com
yasaklı sitelere giriş
aşk kitapları
yabancı şarkılar
sigorta sorgula
https://cozumlec.com
word indir ücretsiz
tiktok jeton hilesi
rastgele görüntülü sohbet
erkek spor ayakkabı
fitness moves
gym workouts
https://marsbahiscasino.org
http://4mcafee.com
http://paydayloansonlineare.com

Отправить комментарий