0

我之前写过一个属性,但是我之前没有写过验证属性。我对这一切如何协同工作感到非常困惑。我已经阅读了大部分关于如何完成此任务的在线教程。但我还有几个问题需要思考。

请记住,我正在尝试编写一个 requiredIf 属性,该属性仅在设置了某个 Jquery 变量时才调用远程函数...顺便说一下,这是一个从视图状态中提取的变量...我想我可以做那部分我的视图模型。但我离题了

1) C# 代码有点混乱。我知道我的属性应该分别扩展 ValidationAttribute、IClientValidatable 类和接口。但是我对每个覆盖的方法应该做什么有点困惑?我正在尝试编写 requiredIf,覆盖这些方法如何帮助我实现这一目标?

2)如果变量不存在,我根本不希望远程函数尝试验证该字段。我不想在我的表单上弹出任何消息。很多教程似乎都围绕着这一点。

3)我很困惑我需要用 jquery 做什么才能将这个函数添加到视图中......我需要向 JQuery 添加什么才能让这个东西工作......这似乎有很多额外的编码当我可以简单地键入一个 jquery 函数,该函数使用相同或更少的编码完成相同的事情时......我知道它还添加了服务器端验证,这很好。但是还是...

这是我在这个等式的 jquery 方面所拥有的......

(function ($) {
    $validator.unobtrusive.adapters.addSingleVal("requiredifattribute", "Dependent");
    $validator.addMethod("requiredifattribute", function (value, element, params) {
        if (!this.optional(element)) {
            var otherProp = $('#' + params)
            return (otherProp.val() != value);
        }
        return true;
    })
}(jQuery));

这是我的属性(基本上是从所需的教程中复制出来的...

[AttributeUsage(AttributeTargets.Property)]
public class RequiredIfAttribute  : ValidationAttribute, IClientValidatable {
    private const string errorMessage = "The {0} is required.";
    //public string 
    private RequiredAttribute innerAttribute = new RequiredAttribute();
    public string DependentProperty { get; set; }
    public object TargetValue { get; set; }

    public RequiredIfAttribute(string dependentProperty, object targetValue){
        this.DependentProperty = dependentProperty;
        this.TargetValue = targetValue;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
        var field = validationContext.ObjectInstance.GetType().GetProperty(DependentProperty);
        if (field != null) {
            var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
            if ((dependentValue == null && TargetValue == null) || (dependentValue.Equals(TargetValue))) {
                if (!innerAttribute.IsValid(value))
                    return new ValidationResult(ErrorMessage);
            }
        }
        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
        ModelClientValidationRule modelClientValidationRule = new ModelClientValidationRule {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            ValidationType = "requiredifattribute"
        };
        modelClientValidationRule.ValidationParameters.Add("dependent", DependentProperty);
        yield return modelClientValidationRule;
    }
}

更新:我所拥有的根本不起作用

这是我的模型中的属性如何使用上述属性进行注释的

    [RequiredIf("isFlagSet", true)]
    [Remote("ValidateHosFin", "EditEncounter", AdditionalFields = "hospitalFin, encflag", ErrorMessage = "Got Damn this is complex!")]
    [MinLength(6)]
    public string HostpitalFinNumber { get; set; }

在我看来,我试图在此验证上键入的值是这样设置的......

   ViewData["ADDENCOREDITTEMP"] = encflag;
   if (encflag == "AddEnc"){
       isFlagSet = true;
   }

我像这样将它嵌入到我的页面中......

@Html.Hidden("isFlagSet", isFlagSet, new { id = "isFlagSet"}) 

我无法让我的表单提交......那个说他刚刚尝试过并让它工作的人,你能发布代码吗?

4

1 回答 1

0

模型:

public class X
{
    [RequiredIf("y", "y", ErrorMessage = "y is not y")]
    public string x { get; set; }

    public string y { get; set; }
}

看法:

@using(Html.BeginForm())
{
    @Html.ValidationSummary()

    @Html.TextBoxFor(m => m.x)
    @Html.TextBoxFor(m => m.y)

    <input type="submit"/>
}

我假设您的验证在服务器端失败?isFlagSet您的视图模型中有属性吗?

于 2012-10-16T18:53:11.700 回答