1

I have a custom DateTextBoxControl in mvc 3. The control is used as

@Html.DateTextBoxFor(x => x.ActiveParty.PartyDetail.InUSASince, 
     new { @class = "span-7 data date-picker", @maxlength = 10 })

In model i am adding validation attribute for the property InUSASince as

[RequiredWhen("NationalityId", new object[] { Nationality_USA }, 
                  true, ErrorMessage = "Date Field is Required.")]
public virtual DateTime? InUSASince { get; set; }

I have registered unobtrusive javascript validator as

    $.validator.unobtrusive.adapters.add("requiredwhen", ["dependentproperty",                    
               "expectedvaluefordependentproperty", "reverse"], function (options) 
    {
        var expectedvaluefordependentproperty = null;
        var reverse = options.params.reverse;
        if (options.params.expectedvaluefordependentproperty.length != 0)
        {
             expectedvaluefordependentproperty = options. params.  
                                         expectedvaluefordependentproperty.split(',');
             var prefix = getModelPrefix(options.element.name);
             dependentproperty = options.params.dependentproperty,
             fullOtherName = appendModelPrefix(dependentproperty, prefix),
             element = $(options.form).find(":input[name='" + fullOtherName + "']");
             options.rules["jqRequiredwhen"] = { dependentelement: element, 
                          expectedvaluefordependentproperty:  
                          expectedvaluefordependentproperty, reverse: reverse };
             if (options.message) {
                  options.messages["jqRequiredwhen"] = options.message; }
         }
     });

when I run the page. it is not showing any validation msg. When i took view source. I can see the control has no validation related attributes.

anyone knows what I am missing ?

Thanks.

4

1 回答 1

2

最后我想出了缺少的东西。在 DateTextBoxFor 的用户控件扩展中,我没有采用为 InUSASince 属性定义的不显眼验证属性。

为此,我们必须使用这些代码行。

 ModelState modelState;

    if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState))
    {
          if (modelState.Errors.Count > 0)
          {
              tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
          }
    }

    var attr = htmlHelper.GetUnobtrusiveValidationAttributes(fullName, modelMetaData);
    tagBuilder.MergeAttributes(attr);

这将为自定义控件添加验证属性。

我希望这对某人有用。

于 2012-04-27T05:13:43.730 回答