简体   繁体   English

mvc unobtrusive验证中的web配置值

[英]web config values in mvc unobtrusive validation

I store values in my web.config. 我将值存储在web.config中。 These are settings for the website. 这些是网站的设置。 For example the event min age limit is 16. I have created my own data annotations to do this and puull back the values using the configurationManager but now I want to create a client side version. 例如,事件最小年龄限制为16.我已经创建了自己的数据注释来执行此操作并使用配置管理器回收值,但现在我想创建客户端版本。

I have this at the moment in a ValidationExtender.js file. 我目前在ValidationExtender.js文件中有这个。

jQuery.validator.addMethod("checkUserAgeOfEvent", function (value, element, param) {
    var dob = $("#DateOfBirth").val();

//do validation here
    if(ConvertToAge(dob) == minAge)
    {
        // do something
    }
    return true;
});

jQuery.validator.unobtrusive.adapters.addBool("checkUserAgeOfEvent");

My problem is that how do I include my value from the web.config or do I have to hard code the min age value? 我的问题是如何从web.config中包含我的值或者我是否必须对最小年龄值进行硬编码? I want to try and avoid this. 我想尽量避免这种情况。

I have created my own data annotations to do this 我已经创建了自己的数据注释来执行此操作

If you implemented the IClientValidatable interface for your custom data annotation you could add custom values to the client as I have illustrated in the following post . 如果您为自定义数据注释实现了IClientValidatable接口,则可以向客户端添加自定义值,如following post

Basically in your GetClientValidationRules method you would pass this minAge to the client: 基本上在您的GetClientValidationRules方法中,您将此minAge传递给客户端:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = this.ErrorMessage,
        ValidationType = "userage",
    };
    rule.ValidationParameters.Add("minAge", ConfigurationManager.AppSettings["MinAge"]);
    yield return rule;
}

which could be easily retrieved on the client: 可以在客户端轻松检索:

jQuery.validator.addMethod(
    "checkUserAgeOfEvent", 
    function (value, element, params) {
        var dob = $("#DateOfBirth").val();
        var minAge = params.minAge;
        if(ConvertToAge(dob) == minAge) {
            // do something
        }
        return true;
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM