Index.html(视图)
<div class="categories_content_container">
@Html.Action("_AddCategory", "Categories")
</div>
_AddCategory.cshtml (部分视图)
<script>
$(document).ready(function () {
$('input[type=submit]').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '@Url.Action("_AddCategory", "Categories")',
dataType: "json",
data: $('form').serialize(),
success: function (result) {
$(".categories_content_container").html(result);
},
error: function () {
}
});
});
});
</script>
@using (Html.BeginForm())
{
// form elements
}
控制器
[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
// DbOperations...
return RedirectToAction("Categories");
}
else
{
// model state is not valid...
return PartialView(viewModel);
}
}
问题:如果操作成功,我希望重定向到另一个页面(类别),但没有任何动作,也没有错误消息。如果操作不成功,则按照我的预期工作。
我该怎么做?如何在使用 AJAX post 的情况下路由到另一页?
return RedirectToAction("Categories");
来进行重定向。如果模型状态无效,则ajax post成功(这是预期的)。我想在控制器操作中重定向,这可能吗?或者如果不行,我该如何在ajax成功时捕获它并重定向到另一个页面。总之,如果DbOperations成功,则重定向到另一页,否则重新加载带有模型的partialView。 - AliRıza Adıyahşi