检查 null 时会话无法正确获取,它按预期工作,但在获取时却无法正确工作

问题描述 投票:0回答:1

当我最后尝试获取学生的数据时,std_id 的会话未正确获取一半。

登录

[HttpPost]
public ActionResult slogin(student s)
{
    student sv = db.students.Where(x => x.std_name == s.std_name && x.std_password == s.std_password).SingleOrDefault();

    //sc.scoree[0] = sv.std_id.ToString();
    //sc.scoree[1] = sv.std_name;

    if (sv == null)
    {
        ViewBag.Message = "Invalid User Name or Password!";
    }
    else
    {
        Session["std_id"] = s.std_id;
        return RedirectToAction("ExamDashboard");
    }

    return View();
}

在下面的代码中,使用调试时,if 条件按预期工作,没有进入 if 块内部,但此后该行的值为 0

Debug.WriteLine("Student ID: " + studentId);

考试结束

public ActionResult EndExam(tbl_questions q)
{
    try
    {
        if (Session["std_id"] == null)
        {
            return RedirectToAction("slogin");
        }

        int studentId = Convert.ToInt32(Session["std_id"]);
        int score = Convert.ToInt32(TempData["score"]);
        int examId = Convert.ToInt32(TempData["examid"]);

        // Debugging statements to inspect values
        Debug.WriteLine("Student ID: " + studentId);
        Debug.WriteLine("Exam ID: " + examId);
        Debug.WriteLine("Score: " + score);

        // Check if any of the required data is null or 0
        if (studentId <= 0 || score < 0 || examId <= 0)
        {
            ViewBag.ErrorMessage = "Error: Invalid data for exam creation.";
            return View();
        }

        tbl_setExam exam = new tbl_setExam();
        exam.exam_date = DateTime.Now;
        exam.exam_fk_stud = studentId;
        exam.exam_name = "Sample Exam"; // You may want to set a proper exam name
        exam.std_score = score;

        db.tbl_setExam.Add(exam);
        db.SaveChanges();

        ViewBag.Score = score; // You can pass the score to the view if needed

        return View();
    }
    catch (Exception ex)
    {
        ViewBag.ErrorMessage = "Error: " + ex.Message;
        return View();
    }
}

我尝试调试但找不到问题。

我正在尝试将最终考试数据插入数据库,但它没有插入任何数据。

asp.net-mvc asp.net-core
1个回答
0
投票

愚蠢的错误发生在这一行

学生 sv = db.students.Where(x => x.std_name == s.std_name && x.std_password == s.std_password).SingleOrDefault();

会话[“std_id”] = s.std_id;

使用 sv.std_id 代替 s.std_id

© www.soinside.com 2019 - 2024. All rights reserved.