簡體   English   中英

如何將JSON對象從另一個視圖發送到視圖

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM