1

Getting an error when using MVC3 Compare attribute against a nested property.

Sample code is as follows:

Model and View Model :

public class Data
{
    public string Input { get; set; }
}

public class DataVM
{
    public Data Data { get; set; }
    [Compare("Data.Input")]
    public string ConfirmInput { get; set; }
}

Controller :

public ActionResult Data() {
    return View(new DataVM());
}

[HttpPost]
public ActionResult Data(FormCollection fc) {
    DataVM vm = new DataVM();
    TryUpdateModel(vm, fc);
    if (ModelState.IsValid){
        return Content("Success!!!");
    }
    return View(vm);
}

View:

@model myth.Models.ViewModels.DataVM

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

@Html.EditorFor(m => m.Data.Input)
@Html.ValidationMessageFor(m => m.Data.Input)
<br />
@Html.EditorFor(m => m.ConfirmInput)
@Html.ValidationMessageFor(m => m.ConfirmInput)
<br />
<input type="submit" value="Save" />
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">    </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

If I use [Compare("Input")], client side validation fails. If I use [Compare("Data.Input")], client side validation works but server side fails. In class CompareAttribute.cs, method

protected override ValidationResult IsValid(...) { .. }, 

fails to find Data.Input Property.

What is the correct way to use Compare for Nested Property comparison?

Sergey K
  • 4,071
  • 2
  • 23
  • 34
Jay
  • 11
  • 2

1 Answers1

2

Change your view model and map back to your entity later:

public class DataVM
{
    public string Input { get; set; }

    [Compare("Input")]
    public string ConfirmInput { get; set; }
}
David Wick
  • 7,055
  • 2
  • 36
  • 38
  • Thanks for the reply. I am doing what you have suggested in production but will like to know how to use compare against nested properties. The reason behind is that the same data model is used across multiple view models and validation rules that are used on the data model need to be copied across to all the view models, something we all will like to avoid. If it is not feasible under current mvc release, then the code for compare attribute needs to be updated for future releases to accommodate nested property validation. –  Sep 08 '11 at 15:55