- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个 RequiredAttribute 的扩展类,它不会发回错误消息。如果我在调试器中检查它,文本就在那里。
public class VierRequired : RequiredAttribute
{
public VierRequired(string controlName)
{
//...
}
public string VierErrorMessage
{
get { return ErrorMessage; }
set { ErrorMessage = value; }
}
// validate true if there is any data at all in the object
public override bool IsValid(object value)
{
if (value != null && !string.IsNullOrEmpty(value.ToString()))
return true;
return false; // base.IsValid(value);
}
}
我是这样调用它的
[VierRequired("FirstName", VierErrorMessage = "Please enter your first name")]
public string FirstName { get; set; }
和 mvc-view
<%: Html.TextBoxFor(model => model.FirstName, new { @class = "formField textBox" })%>
<%: Html.ValidationMessageFor(model => model.FirstName)%>
如果我使用普通的 Required 注释,它会起作用
[Required(ErrorMessage = "Please enter your name")]
public string FirstName { get; set; }
但是自定义不会返回任何错误信息
最佳答案
当我创建自己的 RequiredAttribute
派生项时,我在客户端验证方面也遇到了问题。要修复它,您需要像这样注册您的数据注释:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(VierRequired),
typeof(RequiredAttributeAdapter));
只需在您的 Application_Start()
方法中调用它,客户端验证就会正常工作。
如果在您发布表单时您的属性不起作用,那么这将向我表明您的属性中的逻辑有问题(检查您的 IsValid
方法)。我也不确定你想用你的派生数据注释实现什么;你的逻辑看起来像是在尝试做几乎所有默认属性所做的事情:
摘自 MSDN 文档:
A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.
关于c# - 扩展 MVC RequiredAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12573362/
RequiredAttribute 适用于 string 但不适用于 DateTime。例如: [Required] [DisplayFormat(ConvertEmptyString
我有一个必需的消息,我想给它一个自定义消息,因为默认消息不是很好。该消息必须来自资源文件并已参数化,因此资源文件中的消息将类似于 "The {0} field is required." 我需要能够用
我有一个 RequiredAttribute 的扩展类,它不会发回错误消息。如果我在调试器中检查它,文本就在那里。 public class VierRequired : RequiredAttrib
我的 Code-First 模型中有一个数据库计算字段。我已经用 DatabaseGeneratedAttribute 标记了它。我还需要指定 RequiredAttribute 吗? 换句话说:'r
我有一个 Comment 类,其中有一个 Author 属性: public class Comment : IEquatable { public int ID { get; set; }
我在新的 .NET Core 项目中遇到本地化问题。我有 2 个项目: 带有模型和 DataAnnotations 的 DataAccess 项目(例如 RequiredAttribute) 具有 M
这是我们在 .NET MVC 2 中面临的问题。 我们正在尝试使用 DataAnnotations 来为我们处理模型验证,就像它应该做的那样。我们遇到的唯一问题是我们不想要标准错误消息(因为我们的网站
我正在使用 javascript 非侵入式验证。我有一个 View 模型,我正在将其重新用于多种形式,并且在某些形式中,需要 View 模型上的某些属性。在其他形式上,他们不应该。有没有办法以编程方式
这是我们在 .NET MVC 2 中面临的问题。 我们正在尝试使用 DataAnnotations 来为我们处理模型验证,就像它应该做的那样。我们遇到的唯一问题是我们不想要标准错误消息(因为我们的网站
假设我向我的 API 发送了以下请求: POST http://localhost:4940/api/cars HTTP/1.1 User-Agent: Fiddler Host: localhost
Brad Wilson 发布了有关 ASP.NET MVC 新 ModelMetaData 的精彩博客系列: http://bradwilson.typepad.com/blog/2009/10/as
我试图创建一个自定义版本的 RequiredAttribute 来替换内置的版本,我已经让它适用于具有字符串值的属性,但是对于 DateTime 或整数的属性,例如,默认的 RequiredAttri
我是一名优秀的程序员,十分优秀!