简体   繁体   中英

Better way to implement this rather than storing a value in Session?

In one of my files, I allow the user to select start and end date:

public DateTime? CourseStartDate
        {
            get => PDConvert.ToDateTime(this.tbCourseStartDate.SelectedDate);
            set => this.tbCourseStartDate.SelectedDate = PDConvert.ToDateTimeN(value);
        }

        public DateTime? CourseEndDate
        {
            get => PDConvert.ToDateTime(this.tbCourseEndDate.SelectedDate);
            set => this.tbCourseEndDate.SelectedDate = PDConvert.ToDateTimeN(value);
        }

In this same file,I have a validate function so if end date is less than start date, the user will see an error message.

However, I have another control (in a different file) where if validation fails in the first file, I don't want the control to save.

First File:

private bool Validate()
    {
        if ((this.CourseStartDate != null && this.CourseEndDate != null) && (this.CourseEndDate < this.CourseStartDate))
        {
            lblError.Text = "Course Start Date must be same as or earlier than Course End Date";
            Session["CourseDates"] = "True";
            return false;
        }
        else
        {
            Session["CourseDates"] = null;
        }

        return true;

    }

Second File:

 public void Save()
        {
            if (Session["CourseDates"] == null)
            {
                HistoricalMark marks = new BLLHistMarks().GetHistoricalMarkByRecordId(this.HistStudentMarkId);

                foreach (GridViewRow row in this.gvMarks.Rows)
                {

                    string markType = (row.FindControl("hfType") as HiddenField).Value;
                    string value = (row.FindControl("tbMark") as TextBox).Text;
                    marks.SetMark((int)PDConvert.ToEnum(markType, TMarkType.Other), value);
                }

                new BLLHistMarks().UpdateHistoricalMarkMarks(marks);
            }
        }

Is there a better way to achieve this rather than using Session to store "True" or Null?

You have to persist that data somewhere . Common locations would be in the session variable (like you're doing), or pass it through in the query string with each request, or read / write it in a database. They all have pros and cons. Query string approach, for example can create long urls that can be problematic, but also means that the 'state' is saved in the url if the user bookmarks it.

Session variable is as common as anything else, and is a reasonable way to do what you're trying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM