将创建的数据传递到另一个控制器
本文关键字:另一个 控制器 创建 数据 | 更新日期: 2023-09-27 18:05:28
我使用的是ASP。. NET MVC实体框架和我有一个页面插入数据
public ActionResult Create()
{
return View();
}
// POST: /Home/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="id,firstname,lastname,email,guests,guestfirstname,guestlastname,productInterest,occupancyTimeline,isInvestment,timeSlot,dateSlot")] CP_LC_Preview cp_lc_preview)
{
if (ModelState.IsValid)
{
db.Data.Add(cp_lc_preview);
db.SaveChanges();
return RedirectToAction("Confirm", new { info = cp_lc_preview });
}
return View(cp_lc_preview);
}
我要做的是把刚刚输入的数据传递给另一个控制器来显示。就像一个确认页面。
这是我的方法来确认页面
public ActionResult Confirm()
{
return View();
}
您可以考虑遵循PRG模式。
PRG表示POST - REDIRECT - GET。使用这种方法,在成功保存数据之后,您将在querystring中发出一个具有唯一id的重定向响应,使用该响应,第二个GET操作方法可以再次查询资源并向视图返回一些内容。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="id,firstname,lastname,email,guests,guestfirstname,guestlastname,productInterest,occupancyTimeline,isInvestment,timeSlot,dateSlot")] CP_LC_Preview cp_lc_preview)
{
if (ModelState.IsValid)
{
db.Data.Add(cp_lc_preview);
db.SaveChanges();
var id = cp_lc_preview.Id;
return RedirectToAction("Confirm", new { id = id });
}
return View(cp_lc_preview);
}
和在确认操作方法中,有id参数,并使用该值再次从数据库读取记录,并根据需要使用。
public ActionResult Confirm(int id)
{
var d = db.Data.FirstOrDefault(g=>g.Id==id);
// Use d as needed
// to do : Return something
}
TempData
如果您不希望在url中使用此id,请考虑使用TempData
来传递数据。但是TempData的生命周期很短。一旦读取,数据就消失了。TempData在后台使用Session来存储数据。
TempData["NewItem"] = cp_lc_preview;
return RedirectToAction("Confirm", "controllerName");
和Confirm方法
public ActionResult actionname()
{
var model=TempData["NewItem"] as CP_LC_Preview
// to do : Return something
}
供参考
我如何包含一个模型与RedirectToAction?
可以使用TempData。
TempData["YourData"] = YourData;//persist data for next request
var myModel=TempData["YourData"] as YourData //consume it on the next request
TempData是一个非常短暂的实例,您应该只使用它仅在当前和后续请求期间。
由于TempData以这种方式工作,您需要确定下一个请求将是什么,以及重定向到另一个视图是唯一可以保证这一点的时候。
因此,使用TempData可靠工作的唯一场景是你正在重定向。这是因为重定向杀死当前请求,然后创建一个服务器上提供重定向视图的新请求。
简单地说,Asp。. Net MVC的TempData字典用于数据之间的共享控制器动作。
TempData的值一直存在,直到被读取或当前用户的会话超时。
缺省情况下,TempData将其内容保存到会话状态。
TempData值在读取时被标记为删除。在请求的最后,所有有标记的值将被删除。
的好处是,如果你有多个重定向链,它不会导致TempData清空后,这些值将一直存在,直到您实际使用它们,然后它们将被清除自动自己。