我有這個控制器動作:
[HttpPost]
public ActionResult OrderData(Order order)
{
var result = new { redirectToUrl = Url.Action("SeatSelection", "Orders", new { id = order.ScreeningId }), order };
return Json(result);
}
我正在嘗試將訂單物件傳遞給另一個操作:
public ActionResult SeatSelection(int id, Order order)
{
var screeningInDb = _context.Screenings.Include(s => s.Seats).Single(s => s.Id == order.ScreeningId);
var viewModel = new SeatSelectionViewModel
{
Seats = screeningInDb.Seats,
NumberOfTicketsOrdered = order.NumberOfTicketsOrdered
};
return View("SeatSelection", viewModel);
}
問題是 - 我在SeatSelectionAction 中收到的唯一引數是 id 引數,盡管OrderDataAction 中的 order 物件是有效的。我很確定問題出在我試圖傳遞訂單物件的方式之內,也許是語法問題?
這是我將表單資料發布到OrderDataAction 的方式:
$.ajax({
type: "POST",
url: '@Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(orderData),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
底線 - 我最終要做的是將表單傳遞給將處理資料的控制器操作,然后將新資料傳遞給“SeatSelection”視圖。我在執行此操作時遇到了麻煩,因為我的 post 方法發送 JSON 資料,所以如果有更好的方法來做我想做的事情,我很樂意學習!
uj5u.com熱心網友回復:
您的模型與 SeatSelection 引數簽名不匹配。
嘗試:
$.ajax({
type: "POST",
url: '@Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: `{"order": ${JSON.stringify(orderData)}}`,
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
或者(這只是創建一個 javascript 物件,其中包含兩個簽名屬性):
const sendObj = { id: 0, order: orderData };
$.ajax({
type: "POST",
url: '@Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(sendObj),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
uj5u.com熱心網友回復:
你不能用
window.location.href = ...
因為在這種情況下,瀏覽器總是呼叫 GET 方法,該方法只能將資料保存在帶有原語引數的查詢字串中,并且不會將 Order 轉換為查詢字串引數。這就是為什么你只能得到 id 的原因。
在您的情況下,直接在操作中重定向會容易得多
public ActionResult OrderData(Order order)
{
return RedirectToAction( ( "SeatSelection", "Orders", new { id = order.ScreeningId }), order });
}
或者當它是同一個控制器時,我通常會這樣做
public ActionResult OrderData(Order order)
{
return SeatSelection (order.ScreeningId, order };
}
但由于您使用的是 ajax,它會重定向,但不會更新您的視圖。對于 ajax,您需要一個應該在成功時更新的區域視圖。因此,您只能使用按鈕提交表單而不是 ajax。在這種情況下,一切都會正常進行。
使用 ajax 的另一種方法是嘗試在屬性中拆分訂單并創建查詢字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/359822.html
標籤:C# json 阿贾克斯 asp.net-mvc 模型视图控制器
