【发布时间】:2015-09-29 18:12:07
【问题描述】:
我有一个包含多个表单的页面,每个表单都是一个部分。我想在提交时发布每个部分。如果有错误,我希望验证错误作为主页的一部分显示在部分中,即如果有错误,我不想只在它自己的页面上看到部分。我是否正确地说这种行为只有在 ajax 帖子中才有可能?我如何在没有 ajax 帖子的情况下返回模型状态错误,而只是一个普通的表单帖子?
编辑: 仍然在它自己的页面上看到部分
部分 -
@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") });
}
【问题讨论】:
-
您希望主页上的模型状态错误除了局部错误吗?
-
你只需返回表单的部分视图,并在ajax成功回调中将原始表单替换为返回的html
-
我希望部分模型状态错误,但部分必须像提交表单之前一样显示在主页上,而不是单独显示
-
@StephenMuecke 你能给我一个例子/链接吗?
标签: error-handling asp.net-mvc-5 partial-views