更新HttpContext.Current.Session中的行

时间:2018-12-20 17:47:38

标签: c# asp.net-mvc-2 session-variables

我有一个似乎是MVC2 .NET 3.5项目,其中包含可搜索的索引,其中包含“编辑/删除”操作链接。搜索结果存储在会话中。修改记录后,更改将保留到数据库中,但是在执行操作后返回搜索结果索引时,除非恢复会话,否则它仍显示未修改的缓存记录。有没有办法更新会话中的行?

public class SearchResultService
{
    private CoolRepository cr = new CoolRepository();

    private List<SearchResult> SearchResults
    {
        get
        {
            List<SearchResult> accessCodes;
            if (HttpContext.Current.Session["SearchResults"] != null)
            {
                accessCodes = (List<SearchResult>)HttpContext.Current.Session["SearchResults"];
            }
            else
            {
                //Create accessCodes data store and save in session
                accessCodes = new List<SearchResult>();
                accessCodes = this.InitAccessCodeData();
                HttpContext.Current.Session["SearchResults"] = accessCodes;
            }

            return accessCodes;
        }
    }

    public IQueryable<SearchResult> GetQueryable()
    {
        return this.SearchResults.AsQueryable();
    }

    private List<SearchResult> InitAccessCodeData()
    {
        int agentInfoID = this.cr.FindAgentInfoID();
        var agentInfos = from a in this.cr.cd.AgentInfos
                         where a.ID == agentInfoID
                         select a;


        List<SearchResult> accessCodes;            

       accessCodes = (from c in this.cr.cd.RACodes
                           <!--- ...omitted --->                
                           select new SearchResult
                           {
                               ID = c.ID,
                               Email = c.Email,
                              <!--- ...omitted --->
                           }).OrderByDescending(c => c.ID).ThenBy(c => c.ActivationDate).ToList();          

        return accessCodes;
    }        
}

 public class SearchResult
{
    public int ID { get; set; }        
    public string Code { get; set; }
    public string Email{ get; set; }


    <!--- below properties omitted --->


}

在控制器中执行操作后,我将会话设置为null,因此索引中显示了更改,但是现在它花费很长时间才能重新创建具有这么多记录的会话。

System.Web.HttpContext.Current.Session["SearchResults"] = null; 

编辑:我找到了解决问题的方法

var results = System.Web.HttpContext.Current.Session["SearchResults"];
IList<SearchResult> accessCodes = (IList<SearchResult>)results;
var origionalRow = accessCodes.Where(a => a.ID == id).FirstOrDefault();
var copyRow = origionalRow;
copyRow.IsCancelled = true;
accessCodes.Remove(origionalRow);
accessCodes.Add(copyRow);

System.Web.HttpContext.Current.Session["SearchResults"] = accessCodes;

0 个答案:

没有答案