gpt4 book ai didi

c# - 扩展 MVC RequiredAttribute

转载 作者:太空狗 更新时间:2023-10-29 18:03:26 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com