我仍然是.NET和ASP.NET MVC的新手,而且我曾经有过一些时候可以暂时存储从数据库中检索到的信息,这样它就可以用于后续的服务器请求。客户。我已经开始使用.NET Session来存储这些信息,键入时间戳,然后在我再次点击服务器时使用时间戳检索信息。
所以一个基本用例:
这是我在任何使用Session作为临时存储的情况下开始使用的方案。但是在JS中生成时间戳并不一定安全,整个事情感觉有点......非结构化。我可以使用现有的设计模式,还是采用更简化/安全的方法?任何帮助将不胜感激。
感谢。
答案 0 :(得分:1)
您可以查看将TempData
存储在Session中的数据。当您从TempData
中取出某些内容时,它将在Action执行完后删除。
因此,如果您在一个操作中添加了TempData
内容,那么它将在所有其他操作中生效TempData
,直到再次从TempData请求TempData
。
您也可以致电TempData.Peek("key")
,这会将其保留在内存中,直到您致电TempData["key"]
或TempData.Remove("key")
答案 1 :(得分:1)
好的,我不确定我是否理解正确,因为JS时间戳步骤似乎是多余的。 但这就是我要做的。
public static string SessionReportKey = "Reports";
public static string ReportIDString = "ReportID";
public Dictionary<string, object> SessionReportData
{
get
{
return Session[SessionReportKey] == null ?
new Dictionary<string, object>() :
(Dictionary<string, object>) Session[SessionReportKey];
}
set
{
Session[SessionReportKey] = value;
}
}
public ActionResult PreviewReport()
{
//retrive your data
object reportData = GetData();
//get identifier
string myGUID = new GUID().ToString();
//might only need [SessionReportData.Add(myGUID, reportData);] here
SessionReportData = SessionReportData.Add(myGUID, reportData);
//in your view make a hyperlink to PrintReport action with a
//query string of [?ReportID=<guidvalue>]
ViewBag[ReportIDString] = myGUID;
return View(reportData);
}
public FileContentResult PrintReport()
{
if(SessionReportData[QueryString[ReportIDString]] == null)
{
//error no report in session
return null;
}
return GenerateFileFromData(SessionReportData[QueryString[ReportIDString]]);
}