簡體   English   中英

無法將數據從一種方法傳遞到同一控制器中的另一種方法

[英]Cant pass data from one method to another in same controller

我正在開發MVC應用程序。

我試圖將數據從一種方法傳遞到同一控制器中的另一種方法。

但是數據無法正確傳遞...

請檢查下面的代碼...我正試圖將“創建”列表中的“產品”列表傳遞給“保存數據”方法。

namespace StockWatchScreen.Controllers
{
    public class OrderController : Controller
    {
        public class OrderProduct
        {
            public string SectionCode { get; set; }
            public double Size { get; set; }
            public double Thickness { get; set; }
            public double Length { get; set; }
            public double Quantity { get; set; }   
        }

         public ActionResult Create()
         {
             List<OrderProduct> oProductList = new List<OrderProduct>();

             OrderProduct oProduct = new OrderProduct();
             oProduct.SectionCode = "123";
             oProduct.Length = "123";
             oProduct.Size = "123";
             oProduct.Thickness =  "123";
             oProduct.Quantity = "123";
             oProductList.Add(oProduct);     
            }    

          return RedirectToAction("SaveData", oProductList);           
       }

        public ActionResult SaveData(List<OrderProduct> oProductList)
        {
            ViewBag.ProductList = oProductList;
            ViewBag.OrderNo = "12321#";
            return View();
        }

        }
    }
}

在SaveData方法中,oProductList列表始終顯示為null。

原因是什么?

您需要返回: return SaveData( oProductList); 您無需返回RedirectToAction,並嘗試避免在mvc中使用TempData來使用TempData["oProduct"]並不是一個好習慣。 使用AjaxBeginForm成功可以得到結果return SaveData( oProductList); 並將其放在您想要的位置。也可以使用UpdateTargetId。

您不能在RedirectToAction發送這樣的模型,您應該使用tempdata進行這樣的動作之間的通信

      public ActionResult Create()
      {
             List<OrderProduct> oProductList = new List<OrderProduct>();
             OrderProduct oProduct = new OrderProduct();
             oProduct.SectionCode = "123";
             oProduct.Length = "123";
             oProduct.Size = "123";
             oProduct.Thickness =  "123";
             oProduct.Quantity = "123";
             oProductList.Add(oProduct);
           }

         TempData["oProduct"] = oProductList; 
         return RedirectToAction("SaveData");
        }

並在接收控制器中

    public ActionResult SaveData(List<OrderProduct> oProductList)
    {
        ViewBag.ProductList = TempData["oProduct"] as List<OrderProduct> ;
        ViewBag.OrderNo = "12321#";
        return View();
    }

這是因為RedirectToAction正在執行301重定向,並且實際上是客戶端向/SaveData操作發起Get請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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