ajax呼叫後MVC3重定向到動作
在 ASP.NET MVC3 應用程序中,我在視圖中有一個按鈕。
點擊按鈕時,將呼叫一個函式,並呼叫 jquery ajax 將項目保存到數據庫
function SaveMenuItems() { var encodeditems = $.toJSON(ids);; $.ajax({ type: 'POST', url: '@Url.Action("SaveItems", "Store")', data: 'items=' + encodeditems + '&storeKey=@Model.StoreID', complete: function () { } } }); }我想要的是在項目保存到數據庫後我想重定向到另一個視圖。(重定向到行動)
我怎樣才能做到這一點?
我嘗試
return RedirectToAction("Stores","Store")在函式結束時在控制器中使用SaveItems。但它不工作我還嘗試添加
window.location.replace("/Store/Stores");ajax 呼叫的完整功能,但也沒有工作任何幫助是極大的讚賞
非常感謝
您可以使用 javascript 重定向到新頁面。
window.location.href在 ajax 呼叫的success/complete事件中將值設置為新的 url。var saveUrl = '@Url.Action("SaveItems","Store")'; var newUrl= '@Url.Action("Stores","Store")'; $.ajax({ type: 'POST', url: saveUrl, // Some params omitted success: function(res) { window.location.href = newUrl; }, error: function() { alert('The worst error happened!'); } });或者在
done活動中$.ajax({ url: someVariableWhichStoresTheValidUrl }).done(function (r) { window.location.href = '@Url.Action("Stores","Store")'; });上面的程式碼使用
Url.Action輔助方法來建構正確的相對 url 到 action 方法。如果您的 javascript 程式碼位於外部 javascript 文件中,您應該將 url 建構到應用程序根目錄並將其傳遞給外部 js 文件中的腳本/程式碼,並使用它來建構操作方法的 url,如本文所述。傳遞參數?
如果你想將一些查詢字元串參數傳遞給新的 url,你可以使用這個方法的重載,
Url.Action它也接受路由值來建構帶有查詢字元串的 url。var newUrl = '@Url.Action("Stores","Store", new { productId=2, categoryId=5 })';其中 2 和 5 可以替換為其他一些實數值。
由於這是一個 html 輔助方法,它只能在您的 razor 視圖中工作,而不是在外部 js 文件中。如果您的程式碼在外部 js 文件中,則需要手動建構 url 查詢字元串參數。
在伺服器端生成新的 url
使用 mvc 輔助方法為 action 方法生成正確的 url 總是一個好主意。從您的操作方法中,您可以返回一個 json 結構,該結構具有要重定向的新 url 的屬性。
您可以使用
UrlHelper控制器中的類來執行此操作。[HttpPost] public ActionResult Step8(CreateUser model) { //to do : Save var urlBuilder = new UrlHelper(Request.RequestContext); var url = urlBuilder.Action("Stores", "Store"); return Json(new { status = "success", redirectUrl = url }); }現在在您的 ajax 呼叫的
success/done回調中,只需檢查返回值並根據需要重定向。.done(function(result){ if(result.status==="success") { window.location.href=result.redirectUrl; } else { // show the error message to user } });