我有一个小型的MVC2应用程序,它以两种文化显示:en-US和es-MX.一部分包含用于预先填充模型中当前日期的日期的用户输入.
使用en-US时,日期字段显示为MM/dd/yyyy,可以使用相同的格式更改,而不会导致任何验证错误.
使用es-MX时,日期字段显示为dd/MM/yyyy,但是当以此格式编辑日期时,服务器端验证将失败并显示以下消息:
值'17/05/1991'对日期无效.
关于该消息的第一件事就是它没有本地化.消息本身(我认为我无法控制)和字段的显示名称(我可以控制并在我的代码中本地化).应该以本地化格式显示.
我已经尝试单步执行代码以查看验证失败的确切位置,但它似乎发生在我看不到的一些已编译的MVC或DataAnnotations代码中.
应用程序详细信息:IIS6,ASP.NET 3.5(C#),MVC 2 RTM
样本型号代码:
public class TestVieModel{
[LocalizedDisplayNameDisplayName("TheDateDisplayName", NameResourceType=typeof(Resources.Model.TestViewModel))]
[Required(ErrorMessageResourceName="TheDateValidationMessageRequired", ErrorMessageResourceType=typeof(Resources.Model.TestViewModel))]
[DataType(DataType.Date)]
public DateTime TheDate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
样本控制器操作代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(TestViewModel model) {
if(ModelState.IsValid) { // <--- Always is false when using es-MX and a date foramtted as dd/MM/yyyy.
// Do other stuff
return this.View("Complete", model);
}
// Validation failed, redisplay the form.
return this.View("Enter", model);
}
Run Code Online (Sandbox Code Playgroud)
示例查看代码:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HispanicSweeps.Web.Model.LosMets.EnterViewModel>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML …Run Code Online (Sandbox Code Playgroud) 什么是DataAnnotations和应用程序验证块之间的区别?
我在Silverlight 4应用程序中有一个简单的测试页面,我正在尝试获取自定义验证规则.
我有一个TextBox和一个Button,我在TextBlock中显示验证结果.我的视图模型有一个Name属性,它绑定了TextBox的Text属性.我在Name属性上有两个验证属性, [Required]和[CustomValidation].
当我点击提交按钮时,必需的验证器正确触发,但我的自定义验证器的验证方法内的断点永远不会被命中.我不明白为什么会这样,因为我认为我非常仔细地遵循了MS的例子:http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v = vs.95)的.aspx
以下是视图模型的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using GalaSoft.MvvmLight.Command;
namespace MyProject
{
// custom validation class
public class StartsCapitalValidator
{
public static ValidationResult IsValid(string value)
{
// this code never gets hit
if (value.Length > 0)
{
var valid = (value[0].ToString() == value[0].ToString().ToUpper());
if (!valid)
return new ValidationResult("Name must start with capital letter");
}
return ValidationResult.Success;
}
}
// my view model
public class ValidationTestViewModel …Run Code Online (Sandbox Code Playgroud) 在Microsoft MVC 3.0中,我有一个类:
public class Product{
public string Title {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
此类可以表示为产品或服务,它们之间的唯一区别仅在于查看时的字段标签.
所以我创建了两个类:
public class ProductMetaData
{
[Display(Name = "Product")]
public object Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和
public class ServiceMetaData
{
[Display(Name = "Service")]
public object Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如何在运行时将这些类设置为MetadataType?
------------------------编辑------------------------- -
我发现我们可以通过继承DataAnnotationsModelMetadataProvider和DataAnnotationsModelValidatorProvider类并在这两者中重写GetTypeDescriptor方法来设置/更改类型的元数据,如下所示:
public class xx : DataAnnotationsModelMetadataProvider
{
protected override ICustomTypeDescriptor GetTypeDescriptor(Type type)
{
if (type == typeof(InvoiceItemViewModel))
return (new AssociatedMetadataTypeTypeDescriptionProvider(typeof(InvoiceItemViewModel), typeof(InvoiceItemMetaData))).GetTypeDescriptor(type);
else
return base.GetTypeDescriptor(type);
} …Run Code Online (Sandbox Code Playgroud) 我看到有一些类似的问题,但没有一个能解决我的问题.
我正在使用Entity Framework 4.3开发MVC3应用程序.我有一个英国日期字段,我计划允许用户使用Jquery UI datepicker进行编辑(由于这个博客我得到了工作).
幸运的是,这个博客包含了使用英国格式制作日期选择器的说明,但是,EF验证仍然告诉我需要输入有效的日期格式.很奇怪,它并没有阻止我将日期提交给数据库,只是不显眼的验证开始并显示消息.
目前我有以下数据注释:
[DataType(DataType.Date)]
public System.DateTime Module_Date { get; set; }
Run Code Online (Sandbox Code Playgroud)
但我也试过添加:
[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
Run Code Online (Sandbox Code Playgroud)
这完全没有效果.我希望有人有一个解决方案,因为我不喜欢关闭不引人注意的验证来停止此错误消息.
谢谢
编辑
在@Iridio回答之后,我考虑添加一个模型绑定,实际上从像我这样读过它的几个帖子似乎是正确的做法,但我想出的并没有效果.这是我尝试过的:
public class DateTimeBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
return date;
}
}
Run Code Online (Sandbox Code Playgroud)
Application_Start()在Global.asax.cs文件的方法中使用此方法:
ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());
ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder());
Run Code Online (Sandbox Code Playgroud) c# validation entity-framework data-annotations asp.net-mvc-3
我有以下UIHInt基于attibute:
[AttributeUsage(AttributeTargets.Property)]
public class DropDownListAttribute : UIHintAttribute, IMetadataAware
{
public DropDownListAttribute(string selectListName)
: base(KnownUiHints.DropDown, KnownPresentationLayers.Mvc, selectListName)
{
SelectListName = selectListName;
}
public string SelectListName { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues[KnowMetadataKeys.SelectListName] = SelectListName;
}
}
Run Code Online (Sandbox Code Playgroud)
它的目的是将SelectList分配给要从列表中选择的单值视图模型属性,如下所示:
public class DemoModel: ViewModel
{
[Required]
[DropDownList("LanguageSelect")]
[Display(Name = "Language")]
public int? LanguageId { get; set; }
public SelectList LanguageSelect { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我现在正在使用一些很棒的Golbergian机器和我自己的元数据提供商,但是IMetadataAware.OnMetadataCreated我发现,我觉得我可以简化这个.现在我添加SelectListName到元数据,然后跳过一些箍到a)将SelectList变成一种全局字典,b)在渲染下拉列表时从该字典中获取选择列表.
我想将SelectList本身添加到属性中的模型元数据,即属性适用的属性的本地元数据,但是如何访问该属性或它包含类型?
entity-framework data-annotations entity-framework-5 asp.net-mvc-uihint
我[Display(Name ="name")]在属性中有一个带有set 的类,并且[Table("tableName"]在类的顶部.
现在我正在使用反射来获取这个类的一些信息,我想知道我是否能以某种方式[Display(Name ="name")]向类本身添加一个.
它会是这样的
[Table("MyObjectTable")]
[Display(Name ="My Class Name")] <-------------- New Annotation
public class MyObject
{
[Required]
public int Id { get; set; }
[Display(Name="My Property Name")]
public string PropertyName{ get; set; }
}
Run Code Online (Sandbox Code Playgroud) [Table("UserMaster")]
public class UserMaster
{
public UserMaster()
{
this.Roles = new List<Role>();
}
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public ICollection<Role> Roles { get; set; }
}
[Table("Role")]
public class Role
{
public Role()
{
this.Users = new List<UserMaster>();
}
public int RoleId{ get; set; }
public string Name{ get; set; }
public ICollection<UserMaster> Users { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我使用EntityTypeConfiguration映射这些表,并触发OnModelCreate
this.HasMany(a => a.Roles).WithMany(b => b.Users).Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UsersInRoles"); …Run Code Online (Sandbox Code Playgroud) 我目前正在使用MVC4数据注释来处理验证.我正在开发一个非常国际化的网站,因此我将所有文本保存在资源文件中.
我还想在资源文件中保留正则表达式以进行验证,这样我就可以使用相同的代码来检查,例如,Post Codes(UK)和Zip Codes(US),只需使用不同的RegEx(以及不同名称的资源等) ).
我有以下属性已经从资源文件中提取错误消息.我怎样才能从资源文件中获取正则表达式?
[RegularExpression(@"^[\w]{1,2}[0-9]{1,2}[\w]?\s?[0-9]{1,2}[\w]{1,2}$", ErrorMessageResourceType = typeof(Resources.ValidationMessages), ErrorMessageResourceName = "validPostcode")]
Run Code Online (Sandbox Code Playgroud)
编辑(再次)
我现在在哪里
按照下面的答案和一些额外的搜索,我有以下内容:
在Global.asax.cs我添加了以下行,以确保调用客户端验证
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalisedAttribute), typeof(RegularExpressionAttributeAdapter));
Run Code Online (Sandbox Code Playgroud)
在我的模型中,我调用了属性扩展
[Localised(typeof(Resources.FormValidation), "postcodeRegEx", "postcodeMsg")]
Run Code Online (Sandbox Code Playgroud)
最后,本地化正则表达式验证的属性扩展
public class LocalisedAttribute : RegularExpressionAttribute
{
public LocalisedAttribute(Type resource, string regularExpression, string errorMessage)
: base(GetRegex(regularExpression))
{
ErrorMessageResourceType = resource;
ErrorMessageResourceName = errorMessage;
}
private static string GetRegex(string value)
{
return Resources.FormValidation.ResourceManager.GetString(value);
}
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,但只是我第一次在启动应用程序时使用它.
我将打开另一个问题来解决这个问题 - 它与原始请求没有直接关系,似乎与大多数人的实现没有关系,似乎并不特定于数据注释.
asp.net asp.net-mvc custom-attributes data-annotations asp.net-mvc-4
我正在寻找一种方法来获得从WCF服务生成的WSDL中指定的字符串元素的最大(和/或最小)长度.
我已经查看了WCF数据注释,这对于实现验证非常简洁,但是它没有将约束放入WSDL中,因此客户端不会意识到它们.
是否有一种相对简单的方法可以在WSDL中反映StringLength Data Annotation属性?或者,如果不这样做,另一种以从WCF服务生成WSDL的方式指定约束的方法会包含它吗?
data-annotations ×10
c# ×5
validation ×4
.net ×1
asp.net ×1
asp.net-mvc ×1
block ×1
localization ×1
mapping ×1
mvvm ×1
reflection ×1
silverlight ×1
wcf ×1
web-services ×1
wsdl ×1