この単純フォームの検証はどのようにしたら実現できますか?モデルの検証エラーを正しく処理する
は、私はもともと次のメソッドを持っていた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");
}
しかし、再方向性の間、私は全体のコンテキストを失い、モデルのエラーとすべてを抱えています。このモデル全体の束縛を読んでも、誰かが私がここで間違っていることをすばやく見つけられるなら、それは認められるでしょう。
元の問題は、最初に開いたときに検証エラーを表示するフォームでした。新しい質問を投稿します。どうも。 –
私はフォームアクションによって呼び出されるようにverifyアクションを追加しました。 –