MVC Foolproof validation - Cannot read property 'value' of undefined

两盒软妹~` 提交于 2019-12-12 02:29:08

问题


I am using MVC Foolproof validation in my application. Scenario is I have a dropdownlist named CustomerType with the the following values

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

and I have one more property in my viewmodel public string CompanyAddress{ get; set; }.My goal is to make CompanyAddress required if dropdownlist has values 3 or 4

I have tried the following

   [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;
            }

        }

    }

The above code is working properly on the server side but on the client side i'm getting the following error

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

Validation is being referenced as follows

 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"
                    ));

回答1:


Your validation attribute could not work on the client on the client unless you were to generate a input (say) <input name="IsCompanyAddressRequired" value="false" /> (or value="true" depending on the initial value of customerTypeID) and then dynamically update the value attribute using javascript when the dropdownlist value is changed.

Instead use

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

and delete your IsCompanyAddressRequired property.



来源:https://stackoverflow.com/questions/33910818/mvc-foolproof-validation-cannot-read-property-value-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!