2011-12-16 246 views
0

將數據從控制器傳遞到另一個控制器。這是我在做什麼,但我不認爲這是做這件事的正確方法,plz幫助我修改代碼,它的工作,例如共享/教程..MVC3如何將數據傳遞到控制器的控制器

我使用成員身份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,但我不知道如何把它放在一起......謝謝!

回答

1

您可以直接通過您的UserID參數到控制器的方法,因爲它是一個標準導航流量

RedirectToAction有一個overload,允許您設置routeValues

return RedirectToAction("Create", "Company", new { id = userIdGenerated() });  

而在你CompanyController

public ActionResult Create(int id) { return View(id); } 

既然你將擁有URL您id,那麼你就可以抓住它在您的文章,以及:

[HttpPost] 
public ActionResult Create(int id, CompanyInformation companyinformation) 

或者您可以將其保存到模型CompanyInformation上GET Create

+0

斯特凡喜找到更多的細節,謝謝!感謝你的幫助,你可以通過你的意思來示範我「或者你可以將它保存到GET Create的ModelInformation模型中,這是ModelView嗎?你能否給我提供一個例子...... – Ben 2011-12-16 07:28:48

+0

我的意思是如果你的`CompanyInformation`具有UserId屬性,那麼你可以在你的創建操作`返回視圖(新的CompanyInformation {UserId = id});`中做這樣的事情並把它保存到例如`@ Html.HiddenFor(x => x)的隱藏字段中的視圖。UserId)` – 2011-12-16 07:42:27

相關問題