将数据从控制器传递到另一个控制器。这就是我在做什么,但我不认为这是正确的做法,plz帮我修改代码让它工作,分享示例/教程..
e.g
我正在使用Membership API来创建用户帐户
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");
}
联系控制器
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...
}
我希望我很清楚我想要做什么。也许使用ViewModels,但我不知道如何把它放在一起......谢谢!
答案 0 :(得分:2)
public ActionResult Action1()
{
TempData["key"] =Some_Object;
return RedirectToAction("Action2");
}
public ActionResult Action2()
{
var data= TempData["key"];
}
使用TempData
答案 1 :(得分:1)
您可以将UserID
参数直接传递给控制器的方法,因为它是标准导航流程
RedirectToAction
有一个overload,可让您设置routeValues
。
return RedirectToAction("Create", "Company", new { id = userIdGenerated() });
在CompanyController
public ActionResult Create(int id) { return View(id); }
由于您的网址中包含id
,因此您也可以在帖子中找到它:
[HttpPost]
public ActionResult Create(int id, CompanyInformation companyinformation)
或者您可以将其保留在GET CompanyInformation
Create
中
答案 2 :(得分:1)
您可以使用TempData。
请在以下链接中找到更多详情 http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications