I have a property on my view model that is a custom class with a value property.
e.g.
class mycustomobj
{
public int? Value {get; set; }
}
public class myviewmodel
{
[DefaultablePercentRange]
public property mycustomobj { get; set; }
}
I have a custom range attribute DefaultablePercentRange that I decorate this property with so that I can check apprpiate inputs. Associated with this is the relevant javascript validator for clientside.
The javascript is:
Sys.Mvc.ValidatorRegistry.validators["defaultablePercentRange"] = function (rule) {
var _minimum = rule.ValidationParameters["minimum"];
var _maximum = rule.ValidationParameters["maximum"];
return function (value, context) {
if (!value || !value.length) {
return true; // return true as null values allowed
}
var n = Number.parseLocale(value);
return (!isNaN(n) && _minimum <= n && n <= _maximum);
};
}
I am also using Html.EditorFor on my view with templates so that I can output the property as mycustomobj.Value rather than just mycustomobj . So the view property in html ends up being rendered something like:
<input class="defaultable tiny" default="0" defaultwhen="0" id="mycustomobj_Value" name="mycustomobj.Value" type="text" value="" placeholder="0" style="">
Now my problem is the javascript validation is passing null into my clientside validators function. After a fair amount of investigation I have identified this being because the JSON created for my custom DataAnnotationsModelValidator is not using the full id of the property. For example the JSON created is:
{"FieldName":"mycustomobj","ReplaceValidationMessageContents":true,"ValidationMessageId":"mycustomobj_validationMessage","ValidationRules":[{"ErrorMessage":"This value must be in the range 0 - 100","ValidationParameters":{"minimum":0,"maximum":100},"ValidationType":"defaultablePercentRange"},{"ErrorMessage":"This value must be in the range 0 - 100","ValidationParameters":{"minimum":0,"maximum":100},"ValidationType":"defaultablePercentRange"}]}
Where I need:
{“FieldName”:”mycustomobj.value”,”ReplaceValidationMessageContents”:true,”ValidationMessageId”:”mycustomobj_value_validationMessage”,”ValidationRules”:[{“ErrorMessage”:”This value must be in the range 0 – 100″,”ValidationParameters”:{“minimum”:0,”maximum”:100},”ValidationType”:”defaultablePercentRange”},{“ErrorMessage”:”This value must be in the range 0 – 100″,”ValidationParameters”:{“minimum”:0,”maximum”:100},”ValidationType”:”defaultablePercentRange”}]}
My question is. How can I get the right property name serialized out for the clientside validation so that my clientside validation will work. My serverside works just fine.
Please let me know if anyone needs more info.
I ended up getting around this by using a combination of factors.
This meant that when binding back to the viewmodel on post I can ensure the correct property on mycustomobj was set. And in the javascript the javascript client validation code was being called appropiately as the correct input id was being set.