如何进行简单的表单验证?
我有一个AccountVerificationController,它最初有以下方法:
public ActionResult Index(AccountVerificationModel model)
问题是当最初加载视图时,存在验证错误,因为模型具有如下所示的字段:
public class AccountVerificationModel
{
[Required]
public string MerchantId { get; set; }
[Required]
public string AccountNumber { get; set; }
[Required, StringLength(9, MinimumLength = 9, ErrorMessage = "The Routing Number must be 9 digits")]
}
但是,这不是理想的行为。我希望仅在用户单击验证按钮后才进行验证,因此我更改了表单以在帐户控制器中调用Verify方法。
查看如下;
@using (Html.BeginForm("Verify", "AccountVerification", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>@ViewBag.Title</h2>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.SubMerchantId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.MerchantId, new { htmlAttributes = new { @class = "form-control", placeholder = "MID" } })
@Html.ValidationMessageFor(model => model.MerchantId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.RoutingNumber, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.RoutingNumber, new { htmlAttributes = new { @class = "form-control", placeholder = "9 Digit Routing Number" } })
@Html.ValidationMessageFor(model => model.RoutingNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input name="validate" type="submit" value="Validate" class="btn btn-info"/>
</div>
</div>
</div>
}
现在的挑战是处理模型验证错误。我的控制器结构如下:
public class AccountVerificationController : BaseMvcController
{
public AccountVerificationController()
{
}
public ActionResult Index()
{
return View(new AccountVerificationModel());
}
public ActionResult Verify(AccountVerificationModel model)
{
// do the validation then re-direct......
if (!model.IsValid())
{
return RedirectToAction("Index", model);
}
// otherwise try to validate the account
if (!model.VerificationSuccessful)
{
// repopulate the view with this model...
return RedirectToAction("Index", model);
}
return Redirect("Index");
}
然而,在重新定向期间,我正在失去整个上下文,模型错误等等。阅读整个模型绑定,但如果有人能够快速发现我在这里做错了什么,那将不胜感激。
答案 0 :(得分:1)
好吧,当出现错误时你无法重定向。期。重定向实际上是一个两步过程,即使它看起来似乎无所事事。首先,服务器返回301或302状态代码,其标题值指示客户端应该转到的URL。然后,客户端向该给定URL发出全新请求。这就是为什么没有上下文持续存在的原因。它与第一次请求页面的客户端基本相同。
维护上下文的唯一方法是简单地返回一个视图。这意味着您的Verify
操作需要返回与Index
操作相同的视图。然而,这并不完全理想。我并不完全明白原始问题是什么让您决定首先添加Verify
操作,但如果您在这方面打开一个新问题,这可能会得到解决。您应该回复到Index
行动。