amarsuperstar
amarsuperstar

Reputation: 1783

Model Validation with dictionary

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

Upvotes: 2

Views: 2201

Answers (1)

JasCav
JasCav

Reputation: 34652

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.

Upvotes: 1

Related Questions