gpt4 book ai didi

asp.net-mvc - Action 之间的参数传递

转载 作者:行者123 更新时间:2023-12-05 00:34:49 25 4
gpt4 key购买 nike

我试过这个:

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 中保存数据一样但数据将在读取数据的请求结束时自动删除。
TempDataMSDN

备注:
  • C# 中的通用命名约定将私有(private)变量定义为驼峰式。client而不是 Client .
  • 对于 List<Client>我将使用的变量 clients作为名称而不是 client .
  • 您应该使用 "client" 的资源字符串,因此它不会不同步,这意味着一种方法将数据放入 "Client"而另一个在 "client" 中寻找它或 "Client Data"
  • 关于asp.net-mvc - Action 之间的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10233891/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com