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开发者_如何学Python 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?
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; }
}
精彩评论