[英]Cant pass data from one method to another in same controller
I am developing MVC application. 我正在开发MVC应用程序。
I am trying to pass the data from one method to another method in same controller. 我试图将数据从一种方法传递到同一控制器中的另一种方法。
But data doesn't pass properly... 但是数据无法正确传递...
Please check below code... I am trying to pass the Product list from Create to Save data method. 请检查下面的代码...我正试图将“创建”列表中的“产品”列表传递给“保存数据”方法。
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();
}
}
}
}
In SaveData method, oProductList list shows always null. 在SaveData方法中,oProductList列表始终显示为null。
What is reason ? 原因是什么?
You need to return : return SaveData( oProductList);
您需要返回: return SaveData( oProductList);
.You don't need to return RedirectToAction , and try to avoid using TempData["oProduct"]
using TempData in mvc is not good practice. 您无需返回RedirectToAction,并尝试避免在mvc中使用TempData来使用TempData["oProduct"]
并不是一个好习惯。 Using AjaxBeginForm you on succes you can get result return SaveData( oProductList);
使用AjaxBeginForm成功可以得到结果return SaveData( oProductList);
and put it where you want .also you can use UpdateTargetId. 并将其放在您想要的位置。也可以使用UpdateTargetId。
You can't send model like this in RedirectToAction
, you should use tempdata
for this communicating between actions like this 您不能在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");
}
And in the recieving controller 并在接收控制器中
public ActionResult SaveData(List<OrderProduct> oProductList)
{
ViewBag.ProductList = TempData["oProduct"] as List<OrderProduct> ;
ViewBag.OrderNo = "12321#";
return View();
}
This is because RedirectToAction
is doing a 301
redirection, and it is actually the client initiating a Get
request to the /SaveData
action. 这是因为RedirectToAction
正在执行301
重定向,并且实际上是客户端向/SaveData
操作发起Get
请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.