标签: data-annotations

以强类型方式获取属性的[DisplayName]属性

美好的一天!

我有这样的方法来获取[DisplayName]属性的属性值(直接附加或使用[MetadataType]属性).我在极少数情况下使用它,我需要进入[DisplayName]控制器代码.

public static class MetaDataHelper
{
    public static string GetDisplayName(Type dataType, string fieldName)
    {       
        // First look into attributes on a type and it's parents
        DisplayNameAttribute attr;
        attr = (DisplayNameAttribute)dataType.GetProperty(fieldName).GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault();

        // Look for [MetadataType] attribute in type hierarchy
        // http://stackoverflow.com/questions/1910532/attribute-isdefined-doesnt-see-attributes-applied-with-metadatatype-class
        if (attr == null)
        {
            MetadataTypeAttribute metadataType = (MetadataTypeAttribute)dataType.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();
            if (metadataType != null)
            {
                var property = metadataType.MetadataClassType.GetProperty(fieldName);
                if (property != null)
                {
                    attr = (DisplayNameAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault();
                }
            }
        }
        return …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc data-annotations asp.net-mvc-2

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

指定的值不符合所需的格式yyyy-MM-dd

我有一个使用Data Annotations,Entity-Framework Jquery 2.1.3和Jquery UI 1.11.4的.Net MVC 5应用程序.

当我使用英国格式"dd/MM/YYYY"渲染类型为date的输入的编辑表单时; 使用Google Chrome时出现以下错误消息:

指定值'10/10/2001'不符合所需格式'yyyy-MM-dd'.jQuery的2.1.3.js:5317

模型

public class MyModel
{
    [Column(TypeName = "date"), DataType(DataType.Date), Display(Name = "My date")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public string MyDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

标记

<input class="text-box single-line" data-val="true" data-val-date="The field My date must be a date." id="MyDate" name="MyDate" type="date" value="10/10/2001" />
Run Code Online (Sandbox Code Playgroud)

在输入控件中正确设置了该值,但日期未显示在浏览器中.我首先认为这是jQuery的一个问题,因为它出现了jQuery脚本文件,但在IE和Firefox中测试时一切正常.

然后我认为这是我在Chrome中的区域设置,因为默认情况下Chrome认为每个人都在英国,我将区域设置更改为英国,但仍会出现同样的问题.

一个简单的解决方法是将我的模型中的格式更改为通用格式,但对于英国用户来说,这有点陌生.

有没有办法告诉chrome接受"dd/MM/YYYY"中的日期格式?

asp.net-mvc jquery datetime google-chrome data-annotations

39
推荐指数
3
解决办法
7万
查看次数

如何告知Data Annotations验证器还验证复杂的子属性?

验证父对象时是否可以自动验证复杂的子对象,并将结果包含在已填充的对象中ICollection<ValidationResult>

如果我运行以下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace ConsoleApplication1
{
    public class Person
    {
        [Required]
        public string Name { get; set; }

        public Address Address { get; set; }
    }

    public class Address
    {
        [Required]
        public string Street { get; set; }

        [Required]
        public string City { get; set; }

        [Required]
        public string State { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person
            {
                Name = null,
                Address …
Run Code Online (Sandbox Code Playgroud)

c# validation data-annotations

38
推荐指数
3
解决办法
2万
查看次数

使用DataAnnotations比较两个模型属性

我如何编写一个比较两个字段的自定义ValidationAttribute?这是常见的"输入密码","确认密码"方案.我需要确保两个字段相同并保持一致,我想通过DataAnnotations实现验证.

所以在伪代码中,我正在寻找一种方法来实现如下所示:

public class SignUpModel
{
    [Required]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    [Display(Name = "Re-type Password")]
    [Compare(CompareField = Password, ErrorMessage = "Passwords do not match")]
    public string PasswordConfirm { get; set; }
}

public class CompareAttribute : ValidationAttribute
{
    public CompareAttribute(object propertyToCompare)
    {
        // ??
    }

    public override bool IsValid(object value)
    {
        // ??
    }
}
Run Code Online (Sandbox Code Playgroud)

所以问题是,我如何编码[Compare] ValidationAttribute?

c# validation asp.net-mvc data-annotations

38
推荐指数
3
解决办法
6万
查看次数

使用Validator类验证DataAnnotations

我正在尝试使用Validator类验证使用数据注释修饰的.

当属性应用于同一个类时,它可以正常工作.但是当我尝试使用元数据类时,它不起作用.我应该对Validator做什么,所以它使用元数据类?这是一些代码..

这工作:

public class Persona
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "El nombre es obligatorio")]
    public string Nombre { get; set; }

    [Range(0, int.MaxValue, ErrorMessage="La edad no puede ser negativa")]
    public int Edad { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这不起作用:

[MetadataType(typeof(Persona_Validation))]
public class Persona
{
    public string Nombre { get; set; }
    public int Edad { get; set; }
}

public class Persona_Validation
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "El nombre es obligatorio")]
    public string Nombre …
Run Code Online (Sandbox Code Playgroud)

.net c# validation .net-4.0 data-annotations

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

实体框架4.1 InverseProperty属性

只是想了解更多关于RelatedTo属性的信息,我发现它已被EF 4.1 RC中的ForeignKeyInverseProperty属性所取代.

有没有人知道有关此属性变得有用的场景的任何有用资源?

我应该在导航属性上使用此属性吗?例:

public class Book
{
  public int ID {get; set;}
  public string Title {get; set;}

  [ForeignKey("FK_AuthorID")]
  public Author Author {get; set;}
}  

public class Author
{
  public int ID {get; set;}
  public string Name {get; set;}
  // Should I use InverseProperty on the following property?
  public virtual ICollection<Book> Books {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

c# data-annotations entity-framework-4.1

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

使用AngularJS的ASP.NET MVC验证表单

我正在使用MVC 4和AngularJS(+ twitter bootstrap)中的项目.我通常在我的MVC项目中使用"jQuery.Validate","DataAnnotations"和"Razor".然后我在web.config中启用这些键以验证客户端上模型的属性:

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Run Code Online (Sandbox Code Playgroud)

例如,如果我在我的模型中有这个:

[Required]
[Display(Name = "Your name")]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)

有了这个Cshtml:

@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
Run Code Online (Sandbox Code Playgroud)

html结果将:

<label for="Name">Your name</label>
<input data-val="true" data-val-required="The field Your name is required." id="Name" name="Name" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
Run Code Online (Sandbox Code Playgroud)

但是现在当我使用AngularJS时,我想渲染可能是这样的:

<label for="Name">Your name</label>
<input type="text" ng-model="Name" id="Name" name="Name" required />
<div ng-show="form.Name.$invalid">
   <span ng-show="form.Name.$error.required">The field Your name is required</span>
</div>
Run Code Online (Sandbox Code Playgroud)

我不知道是否有任何助手或"数据注释"来解决这个问题.我知道AngularJS还有很多其他功能:

<div ng-show="form.uEmail.$dirty …
Run Code Online (Sandbox Code Playgroud)

validation asp.net-mvc data-annotations razor angularjs

36
推荐指数
2
解决办法
3万
查看次数

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

该字段必须是数字.如何将此消息更改为其他语言?

如何更改所有int字段的消息,而不是说:

The field must be a number 用英文表示:

El campo tiene que ser numerico 在西班牙语中.

有办法吗?

validation asp.net-mvc localization numbers data-annotations

34
推荐指数
2
解决办法
3万
查看次数

必需属性的DataAnnotation

首先它有效,但今天它失败了!

这是我定义date属性的方法:

[Display(Name = "Date")]
[Required(ErrorMessage = "Date of Submission is required.")]        
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
public DateTime TripDate { get; set; }
Run Code Online (Sandbox Code Playgroud)

它一直在工作.但今天,当我调用相同的ApiController动作时:

[HttpPost]
public HttpResponseMessage SaveNewReport(TripLeaderReportInputModel model)
Run Code Online (Sandbox Code Playgroud)

萤火虫报道:

ExceptionMessage:

"Property 'TripDate' on type 'Whitewater.ViewModels.Report.TripLeaderReportInputModel' 
is invalid. Value-typed properties marked as [Required] must also be marked with
[DataMember(IsRequired=true)] to be recognized as required. Consider attributing the 
declaring type with [DataContract] and the property with [DataMember(IsRequired=true)]."

ExceptionType

"System.InvalidOperationException"
Run Code Online (Sandbox Code Playgroud)

发生了什么?是不是那些[DataContract]WCF?我正在使用REST WebAPIMVC4 …

data-annotations asp.net-mvc-4 asp.net-web-api

34
推荐指数
3
解决办法
2万
查看次数