标签: data-annotations

ASP.NET MVC数据批注验证ErrorMessageResourceType

使用Data Annotations Valition时,一切正常,直到我尝试使用资源.

这是我得到的错误:当前上下文中不存在名称"ErrorMessageResourceType".

我使用的代码:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Microsoft.Web.Mvc;

namespace Project.Models  
{  
    [MetadataType(typeof(LanguageMetaData))]
    public partial class Language
    {
    }

    public class LanguageMetaData
    {
        [Required(ErrorMessageResourceType(typeof(Resources.Errors)), 
                  ErrorMessageResourceName = "IdRequired")]
        public object Id { get; set; }

        [Required(ErrorMessageResourceType(typeof(Resources.Errors)), 
                  ErrorMessageResourceName = "NameRequired")]
        public object Name { get; set; }

        public object Flag { get; set; }
        public object IsDefault { get; set; }
    }

}
Run Code Online (Sandbox Code Playgroud)

我找不到任何错误.更有经验的人可以帮我解决错误吗?

谢谢!

c# validation data-annotations

5
推荐指数
1
解决办法
1万
查看次数

在ASP.net MVC中通过jQuery在客户端本地化验证消息

我正在使用jquery进行客户端验证以及数据注释.一切正常,但我想在数字文本框中输入非数字值时本地化一条消息.对于服务器端验证,可以通过将DefaultModelBinder.ResourceClassKey设置为资源类名称并为PropertyValueInvalid键提供值来完成.

但是对于客户端验证,asp.net mvc正在使用它自己的资源文件,其中包含密钥"ClientDataTypeModelValidatorProvider_FieldMustBeNumeric".使用jQuery.validate在MVC 2中的Custom Server和Client Side Required Validator中描述了我找到的唯一解决方法.该解决方案确实有效,但我想知道是否有更简单或更正确的方法.

谢谢.

validation asp.net-mvc localization jquery-validate data-annotations

5
推荐指数
1
解决办法
1404
查看次数

从ASP.NET MVC 3中的RequiredAttribute加入时,客户端验证不起作用?

我在ASP.NET MVC3中创建了一个这样的继承属性:

public sealed class RequiredFromResourceAttribute : RequiredAttribute
{
    public RequiredFromResourceAttribute(string errorResourceName, string errorResourceTypeName)
    {
        this.ErrorMessageResourceName = errorResourceName;
        this.ErrorMessageResourceType = Type.GetType(errorResourceTypeName);
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

[RequiredFromResource("Title", "Resources.Resource, MyProject.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")]
public string Title { get; set; }
Run Code Online (Sandbox Code Playgroud)

它不起作用,MVC忽略了它.然后我创建一个更简单的类,它继承自RequiredAttribute,如下所示:

public class MyRequiredAttribute : RequiredAttribute
{
}
Run Code Online (Sandbox Code Playgroud)

我就像我说的那样使用它.但它没有再起作用.

尽管如此,所有这些方式都完美地适用于"DisplayNameAtrribute".

问题是什么?

asp.net-mvc data-annotations asp.net-mvc-3

5
推荐指数
1
解决办法
1609
查看次数

为什么好友类用于验证?

我很好奇为什么使用好友类完成数据验证.请考虑以下示例,其中MyEntity是Linq-to-SQL或Linq-to-Entities实体,下面的类是增强实体的部分类.

[MetadataType(typeof(MyEntity.MyEntityMetadata))]
public partial class MyEntity
{
    private class MyEntityMetadata
    {
        [Required(ErrorMessage = "The title is required.")]
        public string Title { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么设计如此?当他们设计DataAnnotations时,为什么选择这种"伙伴模式"?为什么不直接将属性放在实体中?

.net c# data-annotations

5
推荐指数
2
解决办法
2038
查看次数

自定义验证属性在同一字段上多次

如何在同一字段上多次使用相同的自定义验证属性,或者只是为服务器端和客户端验证启用AllowMultiple = true?

我有以下自定义验证属性:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, 
        AllowMultiple = true, Inherited = true)]
public class RequiredIfAttribute : ValidationAttribute,IClientValidatable
{
    public RequiredIfAttribute(string dependentProperties, 
     string dependentValues = "",
     string requiredValue = "val")
     {
     }
}
Run Code Online (Sandbox Code Playgroud)

在dependentProperties中,我可以指定由逗号分隔的多个依赖属性,在dependentValues中,我可以指定依赖属性验证应该处理哪些值,最后在requiredValue中,我可以指定要验证的字段的期望值.

在我的模型中有两个属性LandMark,PinCode和我想使用验证如下:

public string LandMark { get; set; }
[RequiredIf("LandMark","XYZ","500500")]
[RequiredIf("LandMark", "ABC", "500505")]
public string PinCode { get; set; }
Run Code Online (Sandbox Code Playgroud)

这里的值只是例如,因为似乎我可以多次添加属性并且不会出现任何编译错误,我已经在属性中实现了TypeID,如果我从中删除客户端验证,它在服务器端运行良好.但是当我在属性上实现IClientValidatable时,它给了我一个错误:

"不引人注目的客户端验证规则中的验证类型名称必须是唯一的."

任何帮助我该如何解决?

c# jquery-validate data-annotations asp.net-mvc-3

5
推荐指数
2
解决办法
1万
查看次数

无法在MVC3 HTML Helper中获取自定义属性值

我用一个需要来自模型属性的属性值的方法扩展了HTML帮助器.所以我已经定义了一个自定义属性.

    public class ChangeLogFieldAttribute : Attribute {
        public string FieldName { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

在我的模型中使用它就像这样.

    [Display(Name = "Style")]
    [ChangeLogField(FieldName = "styleid")]
    public string Style { get; set; }
Run Code Online (Sandbox Code Playgroud)

在我的帮助方法中,如果属性用于属性,我有以下代码来获取属性的FieldName值.

        var itemName = ((MemberExpression)ex.Body).Member.Name;

        var containerType = html.ViewData.ModelMetadata.ContainerType;
        var attribute = ((ChangeLogFieldAttribute[])containerType.GetProperty(html.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(ChangeLogFieldAttribute), false)).FirstOrDefault();
        if (attribute != null) {
            itemName = attribute.FieldName;
        }
Run Code Online (Sandbox Code Playgroud)

但是,当我到达此代码时,我得到一个异常,因为containerType为null.

我不确定我是否正在做任何正确的事,但是我从大约4个不同的来源中取得了这一点.如果您可以建议解决我的问题或替代方案,我将不胜感激.

谢谢.

更新解决方案

我使用了Darin Dimitrov的解决方案,虽然我不得不调整它.这是我添加的内容.我必须检查属性metatdata的存在,一切都很好.

        var fieldName = ((MemberExpression)ex.Body).Member.Name;

        var metadata = ModelMetadata.FromLambdaExpression(ex, html.ViewData);
        if (metadata.AdditionalValues.ContainsKey("fieldName")) { 
            fieldName = (string)metadata.AdditionalValues["fieldName"];
        }
Run Code Online (Sandbox Code Playgroud)

custom-attributes data-annotations asp.net-mvc-3

5
推荐指数
1
解决办法
3303
查看次数

以编程方式添加数据注释

我正在使用.NET 4的asp mvc3应用程序.

但是我想要使用的模型是在使用.NET 3.5的类库中,并且无法更改.

我可以以编程方式将.NET 4 数据注释添加到我的模型中的某些属性中,以便进行一些简单的验证吗?

c# data-annotations asp.net-mvc-3

5
推荐指数
1
解决办法
8837
查看次数

您如何对数据注释进行单元测试?

其中两个类属性具有以下注释:

    [Key]
    [Column]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }


    [MaxLength(25)]
    public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)

我知道测试Key,Column和Required属性不再是单元测试,它是一个集成测试,因为它依赖于底层数据库,但是你如何测试MaxLength(25)属性呢?

我能想到的其中一个替代方案是在属性中添加代码契约.

更新

正如所建议的那样,我写了以下帮助:

    public class AttributeHelper <T> where T : class
    {
        private Type GivenClass 
        { 
            get { return typeof (T); }
        }

        public bool HasAnnotation(Type annotation)
        {
            return GivenClass.GetCustomAttributes(annotation, true).Single() != null;
        }

        public bool MethodHasAttribute(Type attribute, string target)
        {
           return GivenClass.GetMethod(target).GetCustomAttributes(attribute, true).Count() == 1;
        }

        public bool PropertyHasAttribute(Type attribute, string target)
        {
            return GivenClass.GetProperty(target).GetCustomAttributes(attribute, true).Count() == 1; …
Run Code Online (Sandbox Code Playgroud)

c# tdd unit-testing data-annotations

5
推荐指数
1
解决办法
3231
查看次数

Validator不会识别RegularExpression数据注释

我相信代码是不言自明的.为什么RegularExpression属性不被使用Validator?

License.cs:

public class License {
  [Required]
  [RegularExpression("([0-9A-F]{4}\\-){4}[0-9A-F]{4}")]
  public string Code { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

LicenseTest.cs

[TestMethod]
public void TestValidationOfCodeProperty()
{
    // These tests pass so I know the regex is not the issue
    Assert.IsTrue(Regex.IsMatch("ABCD-EF01-2345-6789-FFFF", "([0-9A-F]{4}\\-){4}[0-9A-F]{4}"));
    Assert.IsFalse(Regex.IsMatch("abcd-ef01-2345-6789-ff00", "([0-9A-F]{4}\\-){4}[0-9A-F]{4}"));
    Assert.IsFalse(Regex.IsMatch("3331313336323034313135302020202020212121", "([0-9A-F]{4}\\-){4}[0-9A-F]{4}"));

    // Setup Validator
    License lic = new License();
    var ctx = new ValidationContext(lic);
    var results = new List<ValidationResult>();

    // Passes - TryValidateObject returns false because the required field is empty
    lic.Code = "";
    Assert.IsFalse(Validator.TryValidateObject(lic, ctx, …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc data-annotations

5
推荐指数
1
解决办法
730
查看次数

EnumDataType()属性验证错误消息未显示

在我的.net core 2.0 Web API中,我在模型属性上使用EnumDataType()验证属性。验证失败时,自定义错误消息为空。我不确定为什么会这样-

EnumDataType(typeof(MyEnum), ErrorMessage = "Custom Error Message")
public MyEnum MyEnumProp {get; set;}
Run Code Online (Sandbox Code Playgroud)

我检查了其他具有[Required],[MinLength]的属性,并且所有属性均生成自定义错误消息。难道我做错了什么?还有其他方法吗?

enums data-annotations asp.net-core asp.net-core-2.0

5
推荐指数
1
解决办法
1867
查看次数