我想比较密码以及指定的密码长度。我正在更新控制器的控制器中存在一些问题,仅当密码为空时,它才返回视图,然后我应用条件来匹配它们,但是我希望像在检查长度时一样自动执行此操作不要在模型中应用其他条件。请帮助我,我的方法有什么问题?
我已经尝试过此代码
控制器:
[AllowAnonymous]
public ActionResult ResetPass()
{
return View();
}
[HttpPost]
[AllowAnonymous]
public ActionResult ResetPass(userPass model, string phoneNumber, String password, String repassword)
{
if (!String.IsNullOrEmpty(model.repassword) && !String.IsNullOrEmpty(model.password)&&model.password==model.repassword )
{
using (var db = new MongoContext())
{
db._database.GetCollection<userPass>("userPass");
var filter = Builders<BsonDocument>.Filter.Eq("_phoneNumber", phoneNumber);
var update = Builders<BsonDocument>.Update
.Set("password", password);
db._database.GetCollection<BsonDocument>("farmers").UpdateOne(filter, update, null);
return RedirectToAction("Login", new {Message = "password has been reset"});
}
}
return View(model);
}
型号:
public class userPass
{
[BsonElement("password")]
[Required(ErrorMessage = "Password is required.")]
[StringLength(8, ErrorMessage = "Password length must be 8.")]
public string password { get; set; }
[BsonElement("repassword")
[Required(ErrorMessage = "Confirmation Password is required.")]
[Compare("password", ErrorMessage = "Password and Confirmation Password must match.")]
public string repassword { get; set; }
}
查看:
@using (Html.BeginForm("ResetPass", "Account", FormMethod.Post))
{
<table>
<tr>
<td>Password</td>
<td>@Html.PasswordFor(m => m.password)</td>
<td>@Html.ValidationMessageFor(m => m.password, "", new { @class = "error" })</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>@Html.PasswordFor(m => m.repassword)</td>
<td>@Html.ValidationMessageFor(m => m.repassword, "", new { @class = "error" })</td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="btn btn-primary block m-b" value="Submit" /></td>
<td></td>
</tr>
</table>
}
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
答案 0 :(得分:1)
[HttpPost]
[AllowAnonymous]
public ActionResult ResetPass(userPass model)
{
if(ModelState.IsValid) {
}
return View(model)
}
只需一点修改。
对于“最小长度”,您可以使用范围属性-
[Range(8, 25, ErrorMessage = "Min Length should be 8")]
第一个参数是minLength,第二个是maxLength
或
[MinLength(8, ErrorMessage = "Min Length should be 8")]
答案 1 :(得分:1)
编辑比较属性。
[Compare(CompareField = password, ErrorMessage = "Password and Confirmation Password must match.")]
这是详细示例:
public class userPass
{
[BsonElement("password")]
[Required(ErrorMessage = "Password is required.")]
[StringLength(8, ErrorMessage = "Password length must be 8.")]
public string password { get; set; }
[BsonElement("repassword")
[Required(ErrorMessage = "Confirmation Password is required.")]
[Compare(CompareField = password, ErrorMessage = "Password and Confirmation Password must match.")]
public string repassword { get; set; }
}