如何从会话状态中获取具有 id 的对象列表并将其显示在下拉列表中?

How to get list of objects which have id from session state and show it in dropdownlist?

我在数据库中有 2 个表

Subject(subjID, subjName, tchID)
Teacher(tchID, tchName)

如何从会话状态中获取具有 tchID 值的主题列表并将其显示在 dropdownlist 中? 我的控制器:

 public ActionResult GetListSubj()
    {
        db = new DatabaseMng();
        Teacher tch = db.Teachers.Find(Session["tchID"].ToString());
        ViewBag.subjID = new SelectList(db.Subjects, "subjID", "subjName");
        return View();
    }

在视图中:

...

@Html.DropDownList("subjID", String.Empty)

这是我的代码,它不完整,因为它 return 所有科目,但我希望科目有 tchID 来自登录视图中的会话状态:

[HttpPost]
    public ActionResult Login(Teacher model, FormCollection f)
    {
        db = new DatabaseMng();
        string id = f["txtID"];
        string pw= f["txtPass"];
        if (ModelState.IsValid)
        {            
                Session["tchID"] = id;
                return RedirectToAction("GetListSubj", "Teacher"); 
        }
        return View();
    }

目前您正在使用 db.Subjects 创建 SelectList 对象,它是主题 table.

中的所有项目

查询时包含 where 子句 db.Subjects。您可以将会话中的值用于 where 子句。

var idFromSession = string.empty;
if (Session["tchID"] != null)
{
    idFromSession = Session["tchID"].ToString();
}
var filterdSubjects = db.Subjects.Where(s=>s.tchID == idFromSession);
// Use filterdSubjects  to build your dropdown.

假设tchID 属性是字符串类型。如果它是数字类型(Int32/Int64),将你的session值转换成数字类型并在你的where子句中使用它。

var idFromSession = 0;
if (Session["tchID"] != null)
{
    idFromSession = Convert.ToInt32(Session["tchID"]);
}
var filterdSubjects = db.Subjects.Where(s=>s.tchID==idFromSession);

您还可以考虑切换到更强大的 strongly typed approach which uses view models 以将数据从您的操作方法传输到视图,而不是依赖动态的东西,例如 ViewBag/ViewData。