【问题标题】:How to save object to session in ASP.NET & access it in View如何在 ASP.NET 中将对象保存到会话并在视图中访问它
【发布时间】:2018-01-26 00:59:55
【问题描述】:

我正在编写 Asp.Net MVC 4 应用程序。我想将模型对象保存到会话中,然后从另一个页面访问它,但不知道该怎么做。可能吗?例如一些代码:

[HttpPost]
    public ActionResult Index(EventDetails obj)
    {

        if (ModelState.IsValid)
        {
            Session["EventDetails"] = obj;
            return RedirectToAction("Index2","Home");
        }
       else return View();

这里事件详情模型代码:

namespace ProjectMVC.Models
{
    public class EventDetails
    {
        [Required]
        public string FirstTeamName { get; set; }
    }
}

所以我想将 EventDetails 对象保存到会话中,然后像普通对象一样在 View 中访问它。像这样的:

@Session["EventDetails"].FirstTeamName

【问题讨论】:

  • 您需要将其转换为您在 oreder 中使用的对象才能访问它的参数,即string name = ((EventDetails)Session["EventDetails"]).FirstTeamName
  • 如果您只想通过单个重定向保留数据,最好使用 TempData 代替。 stackoverflow.com/questions/43939693/…

标签: c# asp.net asp.net-mvc


【解决方案1】:

您需要将其绑定到 ViewModel:

var vm = (EventDetails)Session["EventDetails"];
return View(vm);

在你看来,你只是:

@model EventDetails

@Model.FirstTeamName

【讨论】:

  • Thnx,正是我想要的
猜你喜欢
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多