2012-04-19 59 views
4

之間傳遞我嘗試這樣做:參數動作

public ActionResult Index() // << it starts here 
{ 
    return RedirectToAction("ind", new { name = "aaaaaaa" }); 
} 

[ActionName("ind")] 
public ActionResult Index(string name)// here, name is 'aaaaaaa' 
{ 
    return View(); 
} 

和它的作品..

所以,我嘗試這樣做:

[HttpPost] 
public ActionResult Search(string cnpj) // starts here 
{ 
    List<Client> Client = db.Client // it always find one client 
     .Where(c => cnpj.Equals(c.Cnpj)) 
     .ToList(); 

    return RedirectToAction("Index", Client); // client is not null 
} 

public ActionResult Index(List<Client> Client) //but when goes here, client is always null 
{ 
    if (Client != null) 
     return View(Client); 

    return View(db.Client.ToList()); 
} 

爲什麼會發生?第二個代碼塊有問題嗎?

回答

6

您可以重定向只傳遞原始類型,你可以使用TempData複雜類型。

[HttpPost] 
public ActionResult Search(string cnpj) // starts here 
{ 
    List<Client> Client = db.Client // it always find one client 
     .Where(c => cnpj.Equals(c.Cnpj)) 
     .ToList(); 

    TempData["client"] = Client; //<================= 
    return RedirectToAction("Index"); 
} 

public ActionResult Index() 
{ 
    var Client = TempData["client"]; //<================= 

    if (Client != null) 
     return View(Client); 

    return View(db.Client.ToList()); 
} 

基本上TempData就像在Session保存數據,但該數據將在它被讀出的請求的結束時自動被刪除。

TempDataMSDN

注:

  • C#定義的私人可變共同命名慣例是駱駝情況。 client代替Client
  • 對於List<Client>可變我會用clients的名稱,而不是client
  • 你應該使用資源爲"client"字符串,這樣就不會不同步的,這意味着一個方法,可將數據在"Client"而其他在"client""Client Data"
+1

它承擔提的是,這些都是很大的不同approches各地傳遞數據。默認情況下使用臨時數據提供程序將數據存儲在會話中。另外,當你回來時,臨時數據並不保證在那裏。可能考慮執行操作而不是重定向,而不是重定向,而不是重要 - 在這個主題上,POST是必需的嗎?搜索結果通常是更好地得到... – Paul 2012-04-19 18:01:54

+0

@保羅處理。我想我在答案中提到了它,但謝謝澄清這些缺點! – gdoron 2012-04-19 18:03:49

+0

啊,在我開始寫作時沒有看到你的更新... – Paul 2012-04-19 18:04:27

0

好找,所以你問題是,你是通過客戶端作爲參數,但是你的動作方法預計是一個包含屬性「客戶」的對象。或者,如果存在專門詢問客戶端參數的路由定義,它將按照您寫入的方式工作。

+0

你從哪裏看到一個_「方法期待包含屬性的對象」客戶端「」_我沒有! – gdoron 2012-04-19 18:12:28