我有以下代码
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
[Display(Name = "Password")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
当我显示表单时,客户端验证有效,但是当我在服务器端对其进行测试时,它始终有效(尝试使用Password = pass1234和ConfirmPassword = nonmatchingpassword)
我也尝试过使用http://foolproof.codeplex.com/中的EqualTo之类的其他属性,但存在相同的问题。
我已包含方法
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
if (WebSecurity.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
if (ModelState.IsValid)
{
// register user...
}
model.Countries = this.Countries.FindAll().OrderBy(c => c.Name);
return View(model);
}
这就是我渲染它的方式
@using (Html.BeginForm(null, null, FormMethod.Post, new { @class = "form", @id = "register-form" }))
{
@Html.AntiForgeryToken()
<ul class="form-fields">
...
<li class="form-field">
@Html.LabelFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
@Html.EditorFor(m => m.Password)
</li>
<li class="form-field">
@Html.LabelFor(m => m.ConfirmPassword)
@Html.ValidationMessageFor(m => m.ConfirmPassword)
@Html.EditorFor(m => m.ConfirmPassword)
</li>
...
<li class="form-actions">
<button class="submit">register</button>
</li>
</ul>
}
任何想法可能有什么问题吗?我正在使用MVC4 RC。
最佳答案
这是Microsoft在其默认MVC项目模板中执行的操作:
[PropertiesMustMatch( "Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match." )]
public class RegisterModel
{
[Required]
[DisplayName( "User name" )]
public string UserName { get; set; }
[Required]
[DataType( DataType.EmailAddress )]
[DisplayName( "Email address" )]
public string Email { get; set; }
[Required]
[ValidatePasswordLength]
[DataType( DataType.Password )]
[DisplayName( "Password" )]
public string Password { get; set; }
[Required]
[DataType( DataType.Password )]
[DisplayName( "Confirm password" )]
public string ConfirmPassword { get; set; }
}
我不确定您如何进行服务器端测试。如果这对您不起作用,也许您可以发布失败的测试?
关于c# - MVC比较属性在服务器端不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11766837/