簡體   English   中英

添加模型錯誤MVC后,如何使驗證消息消失?

[英]How do I get the Validation message to disappear after adding a model error MVC?

在我看來,我有一個復選框和一個文本框(如果已選中該復選框),那么我需要在文本框中填充一些文本。 為此,我打電話給

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

僅當復選框返回true且頁面重新顯示時文本框為空時,我才收到正確的消息

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

但是我希望使用后在文本框中鍵入某些內容后文本消失,而用戶不必像使用數據注釋那樣點擊“提交”。 我怎樣才能解決這個問題?

我在實體框架5中使用c#Asp.net 4

ModelState.AddModelError是服務器端驗證,因此直到您發布到服務器,錯誤消息都不會消失。

如果需要描述的功能,則可以定義一個自定義驗證屬性,並將其應用於客戶端和服務器端。 例如,您可以定義“ 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;
        }
    }

在您的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插件在客戶端執行相同的條件驗證。

嘗試使用jquery,將eventListener附加到該字段,並刪除MVC添加到該字段的類CSS並隱藏驗證標簽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM