asp.net-mvc - 未将对象引用设置为 TempData 中对象的实例

标签 asp.net-mvc asp.net-mvc-4 entity-framework-5

 [HttpPost]
        public ActionResult Create(EmployeeEntry employeeentry)
        {
            if (ModelState.IsValid)
            {
                EmployeeEntry employeesales = new EmployeeEntry();
                employeesales.stock_id = employeeentry.stock_id;
                employeesales.quantity = employeeentry.quantity;
                employeesales.total = employeeentry.total;
                employeesales.employeeid = (int)TempData["Name"];

                db.EmployeeEntries.Add(employeesales);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.stock_id = new SelectList(db.AddProduct, "stock_id", "Product_name", employeeentry.stock_id);
            return View(employeeentry);
        }

这是我的代码,将 TempData 转换为整数时出现错误。TempData["Name"] 包含已登录员工的 ID。

 var Result = from a in db.login where a.userName == login.userName && a.Password == login.Password select a.login_id;
                    TempData["Name"] = Result.Single();

                    return RedirectToAction("Index", "EmployeeHome");

我了解 TempData["Name"] 没有值。我该如何解决这个问题。

最佳答案

TempData 用于将数据从当前请求传递到后续请求(意味着从一个页面重定向到另一个页面)。

因此,在您的情况下,Tempdata[“Name”] 仅在 EmployeeHome Controller 的当前操作和索引操作中可用。

因此您需要 Session[“Name”] 代替 Tempdata[“Name”]

喜欢:

var Result = from a in db.login where a.userName == login.userName && 
             a.Password == login.Password select a.login_id;
Session["Name"] = Result.Single();
return RedirectToAction("Index", "EmployeeHome");

还有另一个操作

[HttpPost]
    public ActionResult Create(EmployeeEntry employeeentry)
    {
    …
    employeesales.employeeid = (int)Session["Name"];

关于asp.net-mvc - 未将对象引用设置为 TempData 中对象的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27383373/

相关文章:

c# - 使用具有数据库优先、多层体系结构和基于角色的安全性的 Entity Framework 的示例 .NET C# MVC 项目?

c# - 如何在 Entity Framework 5 Code First 中处理主键

asp.net-mvc - 你能创建一个 int 或 enum 类型的强类型 ASP.NET MVC ViewUserControl 吗?

asp.net-mvc - 查看模型 IEnumerable<> 属性从 post 方法返回 null (未绑定(bind))?

c# - 如何在 asp.net MVC 4 和 MVC 5 中设置默认 Controller

asp.net-mvc - 在 MVC 5 应用程序中使用 autofac 注入(inject) SignalR Hub 的依赖项

c# - 内联编辑验证

mysql - 我应该使用哪种连接? 【EF4.0代码优先】

asp.net-web-api - Breeze - 对象 #<Object> 中的扩展结果没有方法 'getProperty' 查询失败

c# - 如何结合 MVC4 与 EF5 Db 第一个单独的项目