客户端条件验证RequiredIf属性

时间:2014-04-29 08:40:51

标签: jquery asp.net css asp.net-mvc asp.net-mvc-4

我有一个带有两个单选按钮的asp.net MVC 4视图。在页面加载时,使用css隐藏视图的一部分。在视图本身上,当用户选择一个单选按钮时,一旦隐藏了部分并显示其他部分,并且当单击其他单选按钮时,将显示其他部分。我想根据选中的复选框执行条件验证。我创建了RequriredIf属性,但它仅适用于服务器端。代码是:

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

        public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
        {
            this.PropertyName = propertyName;
            this.DesiredValue = desiredvalue;
            this.ErrorMessage = errormessage;
        }

        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() && value == null)
            {
                return new ValidationResult(ErrorMessage);
            }
            return ValidationResult.Success;
        }
    }

以下是我使用此属性的方法:

 [RequiredIf("LocationType", LocationTypeEnum.BuildingOffice, "Please enter building number")]
        public string BuildingNumberName
        {
            get { return _BuildingNumberName; }
            set { _BuildingNumberName = value; }
        }

         [RequiredIf("LocationType", LocationTypeEnum.BuildingOffice, "Please enter floor number")]
        private string _Floor = string.Empty;

        public string Floor
        {
            get { return _Floor; }
            set { _Floor = value; }
        }

        private string _ApartmentOfficeNumber = string.Empty;

         [RequiredIf("LocationType", LocationTypeEnum.BuildingOffice, "Please enter appartment/office number")]
        public string ApartmentOfficeNumber
        {
            get { return _ApartmentOfficeNumber; }
            set { _ApartmentOfficeNumber = value; }
        }

private string _HouseNumber = string.Empty;

        [RequiredIf("LocationType", LocationTypeEnum.VillaHouse, "Please enter house number")]
        public string HouseNumber
        {
            get { return _HouseNumber; }
            set { _HouseNumber = value; }
        }

这有一点缺点:

1)它确实回发,因此用户必须等待回发并修复错误。 2)回发后,隐藏默认部分(使用css)。

我想使用客户端。我需要做什么?

1 个答案:

答案 0 :(得分:-1)

我认为您需要添加到您的web.config文件以启用客户端验证。

<configuration>
  <appSettings>  
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>