c# - 添加模型错误 MVC 后如何使验证消息消失?

标签 c# asp.net-mvc asp.net-mvc-4

在我看来,我有一个复选框和一个文本框,如果复选框被选中,那么我需要在文本框中填充一些文本。为此,我调用

ModelState.AddModelError("item", "Please enter some text.");

仅当复选框返回true且文本框为空时 当我的页面重新显示时,我会收到正确的消息

@Html.ValidationMessageFor(model => model.item)

但我希望文本在用户在文本框中键入内容后消失,而无需用户像数据注释那样点击提交。我该如何解决这个问题?

我正在使用带有 Entity Framework 5 的 c# Asp.net 4

最佳答案

ModelState.AddModelError 是服务器端验证,因此在您发布到服务器之前,错误消息不会消失。

如果您想要您描述的功能,您可以定义一个自定义验证属性并将其应用于客户端和服务器端。例如,您可以定义一个“RequiredIf”自定义验证属性,如果满足某个其他条件(在这种情况下,如果另一个属性为真),它将使一个字段成为必需的:

public class RequiredIfAttribute : RequiredAttribute
    {
        private String PropertyName { get; set; }
        private Object DesiredValue { get; set; }

        public RequiredIfAttribute(String propertyName, Object desiredvalue)
        {
            PropertyName = propertyName;
            DesiredValue = desiredvalue;
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            Object instance = context.ObjectInstance;
            Type type = instance.GetType();
            Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
            if (proprtyvalue.ToString() == DesiredValue.ToString())
            {
                 ValidationResult result = base.IsValid(value, context);
                return result;
            }
            return ValidationResult.Success;
        }
    }

在你的 global.asax 中注册它:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),typeof(RequiredAttributeAdapter);

然后你可以像这样使用它:

public class YourModel {
    // This is the property tied to your checkbox
    public bool YourBooleanProperty { get; set; }

    [RequiredIf("YourBooleanProperty", true)]
    public string Item { get; set; }
}

您还可以利用 JQuery Validate 插件在客户端执行相同的条件验证。

关于c# - 添加模型错误 MVC 后如何使验证消息消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20500736/

相关文章:

asp.net-mvc - 使用 Asp.Net Web Api 和客户过滤器进行单元测试

asp.net-mvc - 在 mvc 4 中使用 wcf 服务的问题

google-chrome - Google Chrome 的 dd-mm-yyyy 日期验证错误

c# - 将字符串添加到字符串数组

c# - 通过Winforms应用程序和PCI合规性调用Paypal

c# - TimeZoneInfo 在 2014 年 11 月 2 日美国东部时间凌晨 2 点提前一个小时递增时区

c# - 从客户端检测到具有潜在危险的 Request.Form 值

asp.net - 触发表单例份验证的 User-Agent header 中的更改

c# - MVC4 与 EF 示例代码与工作单元,通用存储库模式?

c# - JSON.NET MVC 4 WebApi