[英]How do I get the Validation message to disappear after adding a model error MVC?
In my view I have a check box and a text box if the check box is checked then I require the text box to be filled with some text. 在我看来,我有一个复选框和一个文本框(如果已选中该复选框),那么我需要在文本框中填充一些文本。 To do this I call
为此,我打电话给
ModelState.AddModelError("item", "Please enter some text.");
only if the checkbox returns true and the text box isempty when my page re-displays I receive the proper message where I have 仅当复选框返回true且页面重新显示时文本框为空时,我才收到正确的消息
@Html.ValidationMessageFor(model => model.item)
but I would like the text to go away after a use types something in the text box, without the user having to hit submit like it does with data annotation. 但是我希望使用后在文本框中键入某些内容后文本消失,而用户不必像使用数据注释那样点击“提交”。 How can I fix this?
我怎样才能解决这个问题?
I'm using c# Asp.net 4 with entity framework 5 我在实体框架5中使用c#Asp.net 4
ModelState.AddModelError
is server-side validation, so the error message will not go away until you post to the server. ModelState.AddModelError
是服务器端验证,因此直到您发布到服务器,错误消息都不会消失。
If you want the functionality you describe, you can define a custom validation attribute and apply it both client side and server-side. 如果需要描述的功能,则可以定义一个自定义验证属性,并将其应用于客户端和服务器端。 For example, you can define a "RequiredIf" custom validation attribute, which would make a field required if a certain other condition is met (in this case, if another property is true):
例如,您可以定义“ RequiredIf”自定义验证属性,如果满足某些其他条件(在这种情况下,如果另一个属性为true),则该属性将成为必填字段:
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;
}
}
Register it in your global.asax: 在您的global.asax中注册:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),typeof(RequiredAttributeAdapter);
Then you can use it like this: 然后,您可以像这样使用它:
public class YourModel {
// This is the property tied to your checkbox
public bool YourBooleanProperty { get; set; }
[RequiredIf("YourBooleanProperty", true)]
public string Item { get; set; }
}
You could also leverage the JQuery Validate plugin to perform the same conditional validation client-side. 您还可以利用JQuery Validate插件在客户端执行相同的条件验证。
尝试使用jquery,将eventListener附加到该字段,并删除MVC添加到该字段的类CSS并隐藏验证标签
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.