0

MVC Foolproof validation在我的应用程序中使用。场景是我有一个名为 CustomerType 的下拉列表,其中包含以下值

 Id     Name
 1      Student
 2      Non-Employed
 3      Employed
 4      SelfEmployed

我的视图模型中还有一个属性。我的public string CompanyAddress{ get; set; }目标是使 CompanyAddressrequired if下拉列表具有值3 or 4

我试过以下

   [Required(ErrorMessage = "Please select status of the customer", AllowEmptyStrings = false)]
    public int? customerTypeID { get; set; }
    public SelectList customerTypeList { get; set; }

   [RequiredIf("IsCompanyAddressRequired", true, ErrorMessage = "please enter company address")]
    public string CompanyAddress { get; set; }


 public bool IsCompanyAddressRequired
    {
        get
        {
            if (customerTypeID == 3 || customerTypeID == 4)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

    }

上面的代码在服务器端正常工作,但在客户端我收到以下错误

 `Uncaught TypeError: Cannot read property 'value' of undefined`

验证引用如下

 bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/plugins/jQueryVal/jquery.unobtrusive*",
                    "~/plugins/jQueryVal/jquery.validate*",
                    "~/plugins/foolproofValidation/MvcFoolproofJQueryValidation.min.js",
                    "~/plugins/foolproofValidation/mvcfoolproof.unobtrusive.min.js",
                    "~/plugins/foolproofValidation/MvcFoolproofValidation.min.js"
                    ));
4

1 回答 1

7

<input name="IsCompanyAddressRequired" value="false" />除非您要生成输入(例如) (或value="true"取决于 的初始值customerTypeID),然后在下拉列表值更改时使用 javascript 动态更新 value 属性,否则您的验证属性无法在客户端上运行。

而是使用

[RequiredIf("customerTypeID", Operator.GreaterThan, 2, ErrorMessage = "..")]
public string CompanyAddress { get; set; }

并删除您的IsCompanyAddressRequired财产。

于 2015-11-25T09:09:24.427 回答