[英]How send a JSON Object to View from another View
我試圖使用AJAX將JSON對象從索引視圖發送到Controller,而不是從Controller發送到方法New和重定向到New View。
我的JS代碼從索引視圖:
function startStrip(id, name, s_date, num, id_type, price){
if (num == "") {
num = 0;
} else {
num = parseInt(num);
}
var item = {
itemId: parseInt(id),
name: name,
startDate: s_date.split(' ')[0],
startTime: s_date.split(' ')[1],
itemNum: num,
IDItemType: parseInt(id_type),
price:price
}
console.log(item);
$.ajax({
type: 'POST',
url: '@Url.Action("New","Congress")',
data: JSON.stringify(item),
contentType: 'application/json; charset=utf-8',
success: function (response) {
console.log("sucess= "+response);
},
error: function (err) {
console.log("error= "+err);
}
});
}
控制器:
[HttpPost]
public ActionResult New(NewCongressViewModel viewModel)
{
Console.WriteLine(viewModel);
return View(viewModel);
}
問題是控制器返回了HTML代碼,並且沒有將我帶到指示的視圖
您可以使用TempData
將模型數據傳遞給重定向請求。 您可以傳遞簡單類型,例如string,int,Guid等。如果要通過TempData傳遞復雜類型的對象,則可以將對象序列化為字符串並將其傳遞。 針對您的情況,您可以使用:
[HttpPost]
public ActionResult New(NewCongressViewModel viewModel)
{
var complexObj = JsonConvert.SerializeObject(viewModel);
TempData["mymodel"] = complexObj;
return RedirectToAction("New");
}
public ActionResult New()
{
if (TempData["mymodel"] is string complexObj )
{
var getModel= JsonConvert.DeserializeObject<NewCongressViewModel>(complexObj); //Your model values can now be accessed
}
return View();
}
注意: TempData
的值僅在一個請求到另一個請求TempData
持續存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.