views:

31

answers:

1

Hi,

Say I have a model like so:

public class MyViewModel {
  //some properties
  public string MyString {get;set;}
  public Dictionary<string,string> CustomProperties {get;set;}
}

And I am presenting the dictionary property like this:

<%= Html.EditorFor(m => m.CustomProperties["someproperty"]) %>

All is working well, however I have implemented a custom validator to validate the properties of this dictionary, but when returning a ModelValidationResult I can not get the member name referenced correctly (which chould be CustomProperties[someproperty] I believe). All the items in the list which are properties are bound correctly to their errors (I want the error class in the text box so I can highlight it).

Here is my code for the custom validator so far

public class CustomValidator : ModelValidator
{
    public Custom(ModelMetadata metadata, ControllerContext controllerContext) : base(metadata, controllerContext)
    {
    }

    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        if (Metadata.PropertyName.Equals("mystring", StringComparison.OrdinalIgnoreCase))
        {
            yield return new ModelValidationResult() {Message = "normal property validator works!!"};
        }
        else if (Metadata.PropertyName.Equals("customproperties", StringComparison.OrdinalIgnoreCase))
        {

            yield return new ModelValidationResult() { MemberName = "CustomProperties[someproperty]", Message = "nope!" };
        }
    }
}

It appears like something is filling in the MemberName property further up, and ignoring what I put in there

Cheers, Amar

+1  A: 

It appears to me that you are making validation more difficult than it needs to be. Have you taken a look at DataAnnotations which are built into the framework? Scott Gu's blog talks about this. It's a really nice (and easy) way to do validation of models.

JasCav
Yes I am using this at the moment, however I need to extend this a little bit, since my properties in the dictionary are dynamic (as is the schema underneath, but this is out of my control as I a building something over a 3rd party product). I already have structures which will tell me which key has which validation requirements so now I just need to apply this to my dictionary :)
amarsuperstar
I got it working with a Dictionary in the end, however problems further down the line have made me decide to use generated POCO view models so I don't have to work against the framework.
amarsuperstar