问题
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