为了账号安全,请及时绑定邮箱和手机立即绑定

如何维护会话中的数据集合?

如何维护会话中的数据集合?

C#
米琪卡哇伊 2022-11-21 22:06:57
为了开具发票,我通过将选定的时间表存储在浏览器会话中并在用户更新时向该列表添加/删除条目来跟踪与发票关联的时间表条目:GridView 加载所选公司的所有时间表,然后通过更改行样式和选择按钮文本进行指示:private void HighlightInvoiceTimesheets(){    var timesheets = Session["invoiceTimesheets"] as List<Timesheet>;    var invoiceTotalHours = 0;    foreach (var timesheet in timesheets)    {        var tid = timesheet.Id.ToString();        foreach (GridViewRow row in ItemsGrid.Rows)        {            var btn = row.Cells[ItemsGrid.Columns.Count - 1].Controls[0] as LinkButton;            if (ItemsGrid.DataKeys[row.RowIndex].Values["Id"].ToString() == tid)            {                row.CssClass = "success";                btn.Text = "Remove";                int.TryParse(row.Cells[5].Text, out int timesheetHours);                invoiceTotalHours += timesheetHours;            }        }    }    Session["invoiceTotalHours"] = invoiceTotalHours;    BillableHoursLabel.Text = invoiceTotalHours.ToString();}当用户在 GridView 中“选择”一个项目时,它会在 Session 的集合中添加或删除该项目,并相应地更新 GridView:protected void ItemsGrid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e){    // Get the list of timesheets associated with the invoice.    var list = (Session["invoiceTimesheets"] == null) ? new List<Timesheet>() : Session["invoiceTimesheets"] as List<Timesheet>;    // Get the selected timesheet.    int.TryParse(ItemsGrid.DataKeys[e.NewSelectedIndex].Values["Id"].ToString(), out int timesheetId);    var timesheet = timesheetService.GetClearTimesheet(timesheetId);    // Get the select button to update its text.    var btn = ItemsGrid.Rows[e.NewSelectedIndex].Cells[ItemsGrid.Columns.Count - 1].Controls[0] as LinkButton;    // Get the total hours billable for the invoice based on the total hours of the timesheets.    var invoiceTotalHours = (Session["invoiceTotalHours"] == null) ? 0 : int.Parse(Session["invoiceTotalHours"].ToString());}这没有任何错误,但我很困惑为什么list.Remove(timesheet);实际上不更新内存中的列表。因此,会话中的集合不会更新,所做的更改也不会反映在数据库中。
查看完整描述

1 回答

?
梦里花落0921

TA贡献1772条经验 获得超5个赞

这是因为您要删除的时间表与您从中获得的时间表不是同一个对象


var timesheet = timesheetService.GetClearTimesheet(timesheetId);

而不是这个:


if (list.Find(x => x.Id == timesheetId) != null)

{

    // The list contains the selected item, remove it and indicate removed.

    list.Remove(timesheet);

做这个:


var timeSheetSession=list.FirstOrDefault(x => x.Id == timesheetId);

if(timeSheetSession!=null)  list.Remove(timeSheetSession);

这是伪代码,我没有测试过。


查看完整回答
反对 回复 2022-11-21
  • 1 回答
  • 0 关注
  • 56 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信