Note that there are some explanatory texts on larger screens.

plurals
  1. POGet full name of Complex Type from ModelClientValidationRequiredIfRule method in custom ValidationAttribute
    primarykey
    data
    text
    <p>I am using the example at <strong><a href="http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2" rel="nofollow">The Complete Guide To Validation In ASP.NET MVC 3</a></strong> to create a <strong>RequiredIf</strong> validation attribute (it's about 1/3 down the page under the heading of "<strong>A more complex custom validator</strong>"). It all works fine with the exception of one scenario, and that is if I have the need to validate against a complex type. For example, I have the following model:</p> <pre><code>public class MemberDetailModel { public int MemberId { get; set; } // Other model properties here public MemberAddressModel HomeAddress { get; set; } public MemberAddressModel WorkAddress { get; set; } } public class MemberAddressModel { public bool DontUse { get; set; } // Other model properties here [RequiredIf("DontUse", Comparison.IsEqualTo, false)] public string StreetAddress1 { get; set; } } </code></pre> <p>The problem is that when the attribute validation for the StreetAddress property is rendered, it get's decorated with the attribute of <code>data-val-requiredif-other="DontUse"</code>. Unfortunately, since the address is a sub-type of the main model, it needs to be decorated with a name of <strong>HomeAddress_DontUse</strong> and not just <strong>DontUse</strong>.</p> <p>Strangely enough, the validation works fine for server-side validation, but client-side unobtrusive validation fails with an JS error because JS can't find the object with a name of just "DontUse".</p> <p>Therefore, I need to find a way to change the ModelClientValidationRequiredIfRule method to know that the property it is validating is a sub-type of a parent type, and if so, prepend the <code>ParentType_</code> to the "otherProperty" field (e.g. otherProperty becomes <code>HomeAddress_DontUse</code>. </p> <p>I have tried passing in <code>typeof(MemberAddressModel)</code> as a parameter of the attribute, but even when debugging the attribute creation, I can't seem to find any reference to the parent type of HomeAddress or WorkAddress from that type. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload