【发布时间】:2016-05-27 13:27:59
【问题描述】:
如何进行这个简单的表单验证?
我有一个 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")]
}
但是,这不是我们想要的行为。我希望仅在用户单击验证按钮后进行验证,因此我更改了表单以调用帐户控制器中的验证方法。
视图如下;
@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");
}
但是,在重定向期间,我丢失了整个上下文、模型错误和所有内容。阅读整个模型绑定,但如果有人能很快发现我在这里做错了什么,那将不胜感激。
【问题讨论】:
标签: c# validation asp.net-mvc-4 razor