首页 > 解决方案 > 如何将列表中的对象传递给另一个控制器索引函数?

问题描述

我是 asp.net-mvc 的新手。我有一个包含少数用户信息的用户列表,在检查用户输入的用户名与列表中的用户名相同后,如何使用 RedirectToAction 方法将匹配的用户传递给另一个控制器?

登录控制器.cs

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Authorise(Models.User x)
{
    List<User> userList = new List<User>();
    userList.Add(new User { UserName = "A", Password = "A", EmpName ="A", EmpID = "ABC123", EmpEmail = "test@gmail.com", EmpContact = "1300882525" });
    userList.Add(new User { UserName = "B", Password = "B", EmpName = "B", EmpID = "ABC123", EmpEmail = "test@gmail.com", EmpContact = "1300882525" });
    userList.Add(new User { UserName = "C", Password = "C", EmpName = "C", EmpID = "ABC123", EmpEmail = "test@gmail.com", EmpContact = "1300882525" });
    userList.Add(new User { UserName = "E", Password = "E", EmpName = "E", EmpID = "ABC123", EmpEmail = "test@gmail.com", EmpContact = "1300882525" });

    var username = x.UserName;
    var pass = x.Password;

    //String UserName = Request.Form["UserName"];
    //String Password = Request.Form["Password"];

    if (ModelState.IsValid)
    {
        if (!userList.Exists(y => y.UserName == username) && !userList.Exists(y => y.Password == pass))
        {
            TempData["Message"] = "Wrong username or password.";
            return RedirectToAction("Index");
        }
        else if (userList.Exists( y => y.UserName == username) )
        {
            return RedirectToAction("Index", "User");
        }
    }

    return View("Index");
}

public ActionResult LogOut()
{
    Session.Abandon();
    return RedirectToAction("Index", "Login");
}

UserController.cs 我如何在这个控制器中传递对象

public ActionResult Index() 
{            
    List<PurchaseHistory> List1 = new List<PurchaseHistory>();

    List1.Add(new PurchaseHistory { empName = "A", ItemName = "Speaker", DateTime = new DateTime(2018,12,25) });
    List1.Add(new PurchaseHistory { empName = "B", ItemName = "Speaker", DateTime = new DateTime(2018, 12, 25) });
    List1.Add(new PurchaseHistory { empName = "C", ItemName = "Speaker", DateTime = new DateTime(2018, 12, 25) });
    List1.Add(new PurchaseHistory { empName = "C", ItemName = "Laptop", DateTime = new DateTime(2018, 12, 25) });
    List1.Add(new PurchaseHistory { empName = "E", ItemName = "Speaker", DateTime = new DateTime(2018, 12, 25) });
    List1.Add(new PurchaseHistory { empName = "E", ItemName = "Speaker", DateTime = new DateTime(2018, 12, 25) });

    if (List1.Exists( y => y.empName == x.EmpName))
    {
        x.ListPurchaseHistory = List1.FindAll(y => y.empName.Equals(x.EmpName));
    }

    return View(x);
}

标签: c#asp.net-mvc

解决方案


我看到两个选项:

  1. 使用临时数据
  2. 使用匿名对象并更改操作签名:

    RedirectToAction("Index", new { user = your_user })
    
    // ...
    
    public ActionResult Index(User user) 
    

推荐阅读