![](/img/trans.png)
[英]How to use Jquery/Ajax with asp.net MVC 4 with partial view and action with model
[英]ASP.NET MVC Partial view ajax post?
Index.html(查看)
<div class="categories_content_container">
@Html.Action("_AddCategory", "Categories")
</div>
_AddCategory.cshtml(PartialView)
<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帖子路由另一個頁面?
不要從使用AJAX調用的控制器操作重定向。 這毫無用處。 您可以將要重定向的URL作為JsonResult返回:
[HttpPost]
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
// DbOperations...
return Json(new { redirectTo = Url.Action("Categories") });
}
else
{
// model state is not valid...
return PartialView(viewModel);
}
}
然后在客戶端測試此URL的存在並采取相應的行動:
$.ajax({
type: "POST",
url: '@Url.Action("_AddCategory", "Categories")',
data: $('form').serialize(),
success: function (result) {
if (result.redirectTo) {
// The operation was a success on the server as it returned
// a JSON objet with an url property pointing to the location
// you would like to redirect to => now use the window.location.href
// property to redirect the client to this location
window.location.href = result.redirectTo;
} else {
// The server returned a partial view => let's refresh
// the corresponding section of our DOM with it
$(".categories_content_container").html(result);
}
},
error: function () {
}
});
另請注意,我已經從$.ajax()
調用中刪除了dataType: 'json'
參數。 這非常重要,因為我們並不總是返回JSON(在您的情況下,您永遠不會返回JSON,因此這個參數絕對是錯誤的)。 在我的示例中,我們僅在成功的情況下返回JSON,在失敗的情況下返回text/html
(PartialView)。 所以你應該讓jQuery簡單地使用服務器返回的Content-Type
HTTP響應頭來自動推斷出類型,並相應地解析傳遞給你的成功回調的結果參數。
您所做的ajax調用不應該能夠重定向整個頁面。 它僅將數據返回到異步調用。 如果你想進行重定向,我
javascript的重定向方式是window.location
所以你的ajax調用應該是這樣的:
<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) {
window.location='@Url.Action("Categories")';
},
error: function () {
}
});
});
});
</script>
在你的action方法中,不是返回部分或重定向,而是返回Json(true);
public ActionResult _AddCategory(CategoriesViewModel viewModel)
{
if(//success)
{
return Json(true);
}
else
{
return Json(false);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.