加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 06:47:15 所属栏目:asp.Net 来源:网络整理
导读:我试过这个: 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();} 它的工作原理.. 所以,我
我试过这个:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读