微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐