gpt4 book ai didi

c# - MVC 比较属性在服务器端不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 13:57:15 25 4
gpt4 key购买 nike

我有以下代码

[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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com