ASP.NET MVC 4 Unobtrusive validation broken on complex models

安稳与你 提交于 2019-12-10 11:49:18

问题


Alright, so I have a model that looks like:

public class CustomerViewModel {
  public string Password { get; set; }
}

public class CustomerAddViewModel {
  public CustomerViewModel Customer { get; set; }
  [System.ComponentModel.DataAnnotations.Compare("Customer.Password", ErrorMessage = "The confirm password should match")]
  public string ConfirmPassword { get; set; }
}

I get the error message "Could not find a property named Customer.Password" on validation.

I found this SO Question, but it doesn't apply because in the latest version of validation.unobtrusive, the code looks like this:

element = $(options.form).find(":input[name='" + escapeAttributeValue(fullOtherName) + "']")[0];

where the escapeAttributeValue handles all the valid special characters.

I've tried using System.Web.Mvc.Compare instead, but that causes an error while rendering the view.

Any ideas?


回答1:


For the simple reason that the Property "Customer.Password" does not exist. You can define your ViewModel like this:

public class CustomerAddViewModel {
  public CustomerViewModel Customer { get; set; }
  public string Password 
  {
     get
     {
        return this.Customer.Password;
     }
  }
  [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The confirm password should match")]
  public string ConfirmPassword { get; set; }
}



回答2:


The proper "MVC" way of doing what you are doing is to avoid having child objects in your View Model. A View Model is used to provide the minimum information that you require for the specific a action. All the information you require to register / create the customer should be in your View Model, and when you submit your form with the valid information, the action that receives it (or somewhere in the data layer depending on your structure) will create a Customer object based on that View Model.

Of course you can probably still bypass what I just said but the longer you refuse to write those extra lines, the hardest it will be to get out of the hole you are digging.



来源:https://stackoverflow.com/questions/18087358/asp-net-mvc-4-unobtrusive-validation-broken-on-complex-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!