我试过这个:
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()); }
为什么会这样?第二个代码块有问题吗?
解决方法
您只能在重定向中传递基本类型,您可以将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中保存数据一样,但数据将在请求结束时自动删除.
TempData on MSDN
笔记:
> C#中常见的命名约定将私有变量定义为驼峰式.客户而不是客户.>对于List< Client>变量我会使用客户端作为名称而不是客户端.>您应该将资源用于“客户端”字符串,以便它不会失去同步,这意味着一种方法将数据放入“客户端”,而另一种方法在“客户端”或“客户端数据”中查找数据