c# - 将创建的数据传递给另一个 Controller

标签 c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我正在使用 ASP.NET MVC Entity Framework ,并且我有一个要插入数据的页面

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);
        }

我想做的是获取刚刚输入的数据并将其传递给另一个 Controller 进行显示。就像一个确认页面。

这是我的确认页面方法

public ActionResult Confirm()
        {
            return View();
        }

最佳答案

您可以考虑遵循 PRG 模式。

PRG 代表POST - REDIRECT - GET。使用这种方法,在成功保存数据后,您将发出一个在查询字符串中具有唯一 ID 的重定向响应,使用它,第二个 GET 操作方法可以再次查询资源并将某些内容返回给 View 。

[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);
}

并且在您的 Confirm 操作方法中,具有 id 参数并使用该参数的值再次从数据库中读取记录并根据需要使用。

public ActionResult Confirm(int id)
{
   var d = db.Data.FirstOrDefault(g=>g.Id==id);
   // Use d as needed   
   // to do : Return something
}

临时数据

如果您不希望在 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
}

供您引用

How do I include a model with a RedirectToAction?

关于c# - 将创建的数据传递给另一个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39296012/

相关文章:

asp.net - 在 Entity Framework 中的 2 个语句期间锁定表

c# - Ninject:将相同的接口(interface)绑定(bind)到两个实现

.NET ServiceModel.Syndication - 更改 RSS 源的编码

c# - 构造函数参数与方法参数?

c# - 使用 System.ServiceModel 在 Xamarin 中使用 WCF REST 基本身份验证服务

asp.net - 按钮点击方法在页面加载后运行,这意味着页面没有更新,我该如何解决这个问题?

c# - 使用 OpenID(通过 DotNetOpenAuth)以及用户角色和其他成员(member)提供者功能

c# - 如何向 Xelement 添加属性

c# - 旋转 - 使用 LINQ C# 转置 List<List<string>>

jquery - 通过外部拖放将事件添加到 Fullcalendar 时,项目无法获取 id