asp.net-mvc – 在操作之间传递参数

我试过这个:

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>变量我会使用客户端作为名称而不是客户端.>您应该将资源用于“客户端”字符串,以便它不会失去同步,这意味着一种方法将数据放入“客户端”,而另一种方法在“客户端”或“客户端数据”中查找数据

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....