Note that there are some explanatory texts on larger screens.

plurals
  1. POIValidatableObject and Nullable value types
    primarykey
    data
    text
    <p>I have a struct that implements IValidatableObject, which I use for properties on a view model. The validation works fine with non-nullable properties, but if add a property of type Nullable<code>&lt;MyStruct</code>> the IValidatableObject.Validate method is never called for that property, even if it has a value.</p> <p>Is there any way that I trigger the validation on my nullable properties too, or is IValidatableObject not intended to be used with value types?</p> <p>Thanks</p> <hr> <p>Additional information:</p> <p>I wanted to be able to specify units when entering data in my form, e.g. 10m, 100km, 1cm etc. I also wanted to validate that the entered data was within range and of a correct format. My struct converts the string with potentially different units (100cm/100m/1km) into a decimal property which always has the same unit (1/100/1000) and vice-versa.</p> <p>I used IValidatableObject for validation because the validation will always be the same for any instance of MyStruct - I didn't want to add an attribute each time it is used.</p> <p>My model would look something like this: </p> <pre><code>public class MyModel { public MyStruct Ab {get; set;} public MyStruct? Cd {get; set;} } </code></pre> <p>My view is a strongly typed view using the model, which renders my struct as a text box using a display template. When the form is posted, I have a custom model binder to convert the entered string back to my struct. </p> <p>My controller action looks like:</p> <pre><code>public ActionResult MyAction(MyModel model) { //do stuff } </code></pre> <p>The model is bound ok for properties of type MyStruct and Nullable<code>&lt;MyStruct</code>>.</p>
    singulars
    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.
 

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