Passing data from a controller to another controller. this is what i am doing, but I dont think it is the correct way of doing it, plz help me modify the code for it to work, share example/tutorial..
e.g
I am using Membership API to create a user account
public ActionResult Register() { return View(); }
[HttpPost]
public ActionResult Register(RegisterModel model)
{
//creates an account and redirect to CompanyController
//Also I want to store the userId and pass it to the next controller, I am using a session, ok?
Session["userObject"] = userIdGenerated()
return RedirectToAction("Create", "Company");
}
CompanyController:
public ActionResult Create() { return View(); }
[HttpPost]
public ActionResult Create(CompanyInformation companyinformation)
{
//creating company account and I need to store the userid to the company table retrieving from a session
companyinformation.UserID = Session["userObject"].ToString();
db.CompanyInformation.Add(companyinformation);
db.SaveChanges();
//retrieving companyId that was generated and need to pass to the next controller I tried to use "TempData["companyId"] = companyinformation.CompanyInformationID" But the data is no longer found on httpPost
return RedirectToAction("Create", "Contact");
}
Contact controller
public ActionResult Create()
{
//I tried using ViewBag to store the data from TempDate but the data is no longer found on httpPost
ViewBag.companyId = TempData["companyId"].ToString();
return View();
}
[HttpPost]
public ActionResult Create(CompanyContact companycontact)
{
companycontact.CompanyInformationID = ???? How do I get the companyId?
db.CompanyContacts.Add(companycontact);
db.SaveChanges();
//Redirect to the next controller...
}
I hope it is clear what I am trying to do. Maybe use ViewModels but I am not sure how to put it together… Thanks!
You can pass your
UserIDparameter directly to your controller’s method as it was a standard navigation flowRedirectToActionhas one overload that allows you to setrouteValues.And in your
CompanyControllerSince you will have your
idin the URL, then you would be able to catch it in your post as well:Or you can persist it into the model
CompanyInformationon GETCreate