【问题标题】:MVC custom validation attributeMVC 自定义验证属性
【发布时间】:2013-05-30 08:03:32
【问题描述】:

服务器触发 ValidationResult 时是否可以获得 HTML 自定义属性(客户端)。

我就是这样

模型类:

    public class Model_Test
{
    [Age(18,50)]
    [Display(Name = "My Age")]
    public int Age { get; set; }
}

HTML:

@model CustomValidation.Models.Model_Test
@using (@Html.BeginForm("Index","Test"))
{
    @Html.TextBoxFor(m => m.Age, new { @myValidate="Yes" })
    @Html.TextBoxFor(m => m.Age, new { @myValidate="No" })
    <input type="submit" />
}

自定义属性类:

    public class AgeAttribute : ValidationAttribute
    {
        private readonly int _MinAge = 0;
        private readonly int _MaxAge = 0;
        private const string errorMsg = "{0} must at least {1} or not more than {2}";

        public AgeAttribute(int MinAge, int MaxAge)
            : base(() => errorMsg)
        {
            _MinAge = MinAge;
            _MaxAge = MaxAge;
        }

        //Server-Side Validation
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {



        **// Can we get the HTML Attribute from client side and implement some condition at here???
        // etc...
        // if (html.attribute("myValidate") == "Yes") {
        //    *condition......*
        // } else {
        //    *condition......***
        // }



            if (value != null)
            {
                int data = (int)value;
                if (!(data > (int)_MinAge && data < (int)_MaxAge))
                {
                    return new ValidationResult(null);
                }
            }
            return ValidationResult.Success;
        }
    }

在我的代码中,我得到了 2 个 textboxes 并且每个都具有自定义属性 "myValidate="Yes/No"
我可以将此属性带到服务器端 ValidationResult 以进行验证吗?如果没有,还有其他合适的方法吗?

【问题讨论】:

  • 我不明白您为什么要拥有两个具有相同属性的文本框和一个没有验证的文本框?看起来很奇怪
  • 其实我的目的是创建一个动态表 IEnumerable 让用户在年龄属性上添加行并填写一些值,每一行可能有不同的条件。

标签: asp.net-mvc validation attributes


【解决方案1】:

您走在正确的轨道上,但让一个字段具有验证而另一个字段不具有验证的最佳方法是使用两个单独的属性并仅使用自定义属性注释一个:

public class Model_Test
{
    [Age(18,50)]
    [Display(Name = "My Age")]
    public int Age { get; set; }

    [Display(Name = "Another age")]
    public int AnotherAge { get; set; }
}

然后在您的控制器中,您可以对属性做您喜欢的事情,避免让您的验证代码变得更复杂。

【讨论】:

  • 嗨@Stokedout,感谢您的回复。但我不想将属性分成两部分。实际上我的目的是创建一个动态表IEnumerable&lt;CustomValidation.Models.Model_Test&gt; 让用户添加行并在年龄属性上填写一些值,并且每一行可能有不同的条件。这就是为什么我在考虑如何让服务器端决定应该使用哪个条件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2014-11-03
相关资源
最近更新 更多