本文介绍了ASP.Net MVC的核心 - 自定义属性客户端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MVC框架的自定义验证以前的版本将通过实施 IClientValidatable GetClientValidationRules 方法来实现。



然而在ASP.Net MVC核心的,虽然我们确实有 IClientModelValidator 这一个定义非常类似的方法。 。其中,永远不会被称为但是实施



所以 - ?我们如何在ASP.NET MVC核心的自定义特性实现客户端验证


解决方案

IClientModelValidator 其实是在正确的接口。我做了以下人为样本实施



注意:
有一个的来RC1和RC2之间的 IClientModelValidator 接口。这两个选项介绍如下。 - 的代码的其余部分是两个版本之间的相同



属性(RC2和以后)



[AttributeUsage(AttributeTargets.Property,的AllowMultiple = FALSE,继承= FALSE)]
公共密封类CannotBeRedAttribute:ValidationAttribute,IClientModelValidator
{
公众覆盖BOOL的IsValid(对象的值)
{
VAR消息=值串;
返回消息.ToUpper()==红?;
}

公共无效AddValidation(ClientModelValidationContext上下文)
{
MergeAttribute(context.Attributes,数据-VAL,真);
变种的errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes,数据-VAL-cannotbered的ErrorMessage);
}

私人布尔MergeAttribute(
的IDictionary<字符串,字符串>属性,
串键,
字符串值)
{
如果(attributes.ContainsKey(密钥))
{
返回false;
}
attributes.Add(键,值);
返回真;
}
}



属性(RC1)



[AttributeUsage(AttributeTargets.Property,的AllowMultiple = FALSE,继承= FALSE)]
公共密封类CannotBeRedAttribute:ValidationAttribute ,IClientModelValidator
{
公众覆盖BOOL的IsValid(对象的值)
{
VAR消息=值串;
返回消息.ToUpper()==红?;
}

公开的IEnumerable< ModelClientValidationRule> GetClientValidationRules(
ClientModelValidationContext上下文)
{
收益回报新ModelClientValidationRule(
cannotbered,
FormatErrorMessage(的ErrorMessage));
}
}



模型



公共类ContactModel
{
[CannotBeRed(的ErrorMessage =红色是不允许的!)]
酒店的公共字符串消息{搞定;组; }
}



查看



  @model WebApplication22.Models.ContactModel 

< ASP形式的行动=联系的方法=后>
<标签ASP换=消息>< /标签>
<输入ASP换=消息/>
<跨度ASP验证换=消息>< / SPAN>
<输入类型=提交值=保存/>
< /表及GT;

@section脚本{
<脚本SRC =〜/ lib中/ jQuery的验证/距离/ jquery.validate.min.js>< / SCRIPT>
<脚本SRC =〜/ lib中/ jQuery的验证 - 不显眼/ jquery.validate.unobtrusive.min.js>< / SCRIPT>
<脚本>
$ .validator.addMethod(cannotbered,
功能(价值元素,参数){
返回value.toUpperCase()==RED!
}) ;

$ .validator.unobtrusive.adapters.add(cannotbered,[],功能(选件){
options.rules.cannotbered = {};
options.messages [cannotbered] = options.message;
});
< / SCRIPT>
}


In previous versions of the MVC framework custom validation would be achieved through implementing IClientValidatable and the GetClientValidationRules method.

However in ASP.Net Core MVC we do not have this interface, although we do have IClientModelValidator which a defining a very similar method. The implementation of which never gets called however.

So - how do we implement client-side validation for a custom attribute in ASP.NET Core MVC?

解决方案

The IClientModelValidator is in fact the right interface. I've made a contrived sample implementation below.

Note:There was a breaking change to the IClientModelValidator interface between RC1 and RC2. Both options are presented below - the rest of the code is the same between both versions.

Attribute (RC2 and beyond)

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class CannotBeRedAttribute : ValidationAttribute, IClientModelValidator
{
    public override bool IsValid(object value)
    {
        var message = value as string;
        return message?.ToUpper() == "RED";
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val", "true");
        var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
        MergeAttribute(context.Attributes, "data-val-cannotbered", ErrorMessage);
    }

    private bool MergeAttribute(
        IDictionary<string, string> attributes,
        string key,
        string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }
}

Attribute (RC1)

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public sealed class CannotBeRedAttribute : ValidationAttribute, IClientModelValidator
{
    public override bool IsValid(object value)
    {
        var message = value as string;
        return message?.ToUpper() == "RED";
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
        ClientModelValidationContext context)
    {
        yield return new ModelClientValidationRule(
            "cannotbered",
            FormatErrorMessage(ErrorMessage));
    }
}

Model

public class ContactModel
{
    [CannotBeRed(ErrorMessage = "Red is not allowed!")]
    public string Message { get; set; }
}

View

@model WebApplication22.Models.ContactModel

<form asp-action="Contact" method="post">
    <label asp-for="Message"></label>
    <input asp-for="Message" />
    <span asp-validation-for="Message"></span>
    <input type="submit" value="Save" />
</form>

@section scripts {
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
    <script>
        $.validator.addMethod("cannotbered",
            function (value, element, parameters) {
                return value.toUpperCase() !== "RED";
            });

        $.validator.unobtrusive.adapters.add("cannotbered", [], function (options) {
            options.rules.cannotbered = {};
            options.messages["cannotbered"] = options.message;
        });
    </script>
}

这篇关于ASP.Net MVC的核心 - 自定义属性客户端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:29