ModelState.IsValid是否适用于ajax调用?

时间:2013-02-08 11:37:49

标签: ajax validation asp.net-mvc-4

模特:

public class ChangePasswordModel
{
    //User profile key
    public string UserName { get; set; }

    [Required(ErrorMessage = " Please Enter Current Password ")]
    public string OldPassword { get; set; }

    [Required(ErrorMessage = " Please Enter a New Password ")]
    [StringLength(20, MinimumLength = 6, ErrorMessage = "The {0} must be at least {2} and no longer then {1} characters long.")]
    public string NewPassword { get; set; }

    [Required(ErrorMessage = " Please Re-enter a New Password ")]
    [MustBeValidator(MustBeValidator.Condition.EqualTo, "newpassword", ErrorMessage = "Please, confirm password")]
    public string ReNewPassword { get; set; } 
}

ajax调用安全apicontroller:

    [System.Web.Mvc.HttpPost]
    public ActionResult ChangePassword(ChangePasswordModel change)
    {

        if (!ModelState.IsValid)
        {
问题是,即使“ReNewPassword”中的“NewPassword”差异我得到了ModelState.IsValid = true

1 个答案:

答案 0 :(得分:1)

我不知道MustBeValidator是什么,但您可以尝试在ASP.NET MVC 3中使用标准属性:

[Required(ErrorMessage = " Please Re-enter a New Password ")]
[Compare("NewPassword", ErrorMessage = "Please, confirm password")]
public string ReNewPassword { get; set; }