我有一个用户表,当用户登录时(这部分我已经完成)我需要从表中提取所有条目并以某种方式存储它们,然后在视图中将用户重定向到I需要遍历存储的表。
public class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserAccount>().ToTable("User");
}
public System.Data.Entity.DbSet<WebApplication9.Models.UserAccount> Users { get; set; }
}
public class UserAccount
{
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public string UserPassword { get; set; }
}
[HttpPost]
public ActionResult Login(UserAccount user)
{
using (MyDbContext db = new MyDbContext())
{
var usr = db.Users.SingleOrDefault(u => u.UserName == user.UserName && u.UserPassword = user.UserPassword);
if (usr != null)
{
return RedirectToAction("LoggedIn");
}
}
return View();
}
我的登录工作正常,但我想以某种方式保存整个用户表,然后循环遍历它并在我的loggedin
视图中执行操作。
答案 0 :(得分:1)
您可以将其存储在Session或TempData变量中:
[HttpPost]
public ActionResult Login(UserAccount user)
{
using (MyDbContext db = new MyDbContext())
{
Session["userList"] = db.Users.ToList();
//or TempData["userList"] = db.Users.ToList();
var usr = db.Users.SingleOrDefault(u => u.UserName == user.UserName && u.UserPassword = user.UserPassword);
if (usr != null)
{
return RedirectToAction("LoggedIn");
}
}
return View();
}
要检索此数据并在视图中发送,请使用ViewBag:
ViewBag.userList= Session["userList"];
// or ViewBag.userList= TempData["userList"];
循环浏览此数据 -
@{ var userList= (List<UserAccount>)ViewBag.userList; }
@foreach (var item in userList)
{
<p>@item.UserName</p>
<p>@item.Password</p>
}