在我看来,我有一个复选框和一个文本框,如果复选框被选中,那么我需要在文本框中填充一些文本。为此,我调用
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/