私は部分的に複数のフォームを持つページを持っています。私は提出時に各部分を投稿したいと思います。エラーがある場合は、検証エラーをメインページの一部として部分的に表示する必要があります。つまり、エラーがある場合は、部分ページを自分のページに表示したくありません。私はこの動作がajax投稿でのみ可能であると言って正しいですか?どのように私はajaxのポスト、通常のフォームの投稿なしでモデル状態のエラーを返すだろうか?親ページにエラーが表示されたmvcの部分表示を表示
編集: まだ
部分それ自身のページの部分を見て -
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "LoginForm" }))
{
@Html.ValidationMessage("InvalidUserNamePassword")
<fieldset class="fieldset">
<div>
<label for="form-field-user_id">User ID</label>
<span>
@Html.TextBoxFor(x => x.Username, new { @class = "form-field__input form-field__input--text", @id = "form-field-user_id"})
</span>
</div>
</fieldset>
<div class="form-field__button">
<button id="loginButton" type="submit" class="button button--primary">Login</button>
</div>
}
<script>
$('#loginButton').click(function() {
$.ajax({
type: "POST",
url: '@Url.Action("Login", "Account")',
data: $('form').serialize(),
success: function (result) {
if (result.redirectTo) {
window.location.href = result.redirectTo;
} else {
$("#LoginForm").html(result);
}
},
error: function() {
$("#LoginForm").html(result);
}
});
});
</script>
コントローラ -
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (!ModelState.IsValid)
{
return PartialView("~/Views/Account/_Login.cshtml", model);
}
return Json(new { redirectTo = Url.Action("Index", "Profile") });
}
メインページのモデル状態エラーを部分的なものと区別したい場合は、 – lazy
フォームの部分的なビューを返し、ajax成功のコールバックで元のフォームを返されたhtmlに置き換えます。 –
モデル状態エラーを部分的な、bu部分的にメインページに表示する必要があります。それは、フォーム提出前であって、それ自体ではありません。 –