user979331 user979331 - 3 months ago 7
ASP.NET (C#) Question

Pass created data to another controller

I am using ASP.NET MVC Entity Framework and I have a page to insert data

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


What I am trying to do is take that data that was just entered and pass it to another controller to display. like a confirmation page.

Here is my method for the confirm page

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

Answer

You may consider following the PRG pattern.

PRG stands for POST - REDIRECT - GET. With this approach,After you successfully save the data, you will issue a redirect response with a unique id in the querystring, using which the second GET action method can query the resource again and return something to the 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);
}

and in your Confirm action method, have id parameter and using the value of that read the record from the db again and use as needed.

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

TempData

If you do not prefer to have this id in the url, consider using TempData to pass the data. But TempData has a short life span. Once read, the data is gone. TempData uses Session behind the scene to store the data.

TempData["NewItem"] = cp_lc_preview;
return RedirectToAction("Confirm", "controllerName");

and in the Confirm method

public ActionResult actionname()
{      
  var model=TempData["NewItem"] as CP_LC_Preview 
  // to do : Return something
}

For your reference

How do I include a model with a RedirectToAction?

Comments