【问题标题】:Filter By Id in asp.net mvc在 asp.net mvc 中按 ID 过滤
【发布时间】:2019-11-14 03:26:30
【问题描述】:

当我使用 where 条件数据未显示在表格或页面中时,我遇到了过滤数据问题。

我有三个表 GroupsSubgroupsStudents

首先我选择组然后我选择子组并从子组学生表中显示

这是我的控制器:

public ActionResult Index(int? id)
{
    var students = db.Students.AsQueryable()
        .Include(s => s.Groups)
        .Include(s => s.Subgroups)
        .Include(s => s.Schedules)
        .Include(s => s.Teachers);

    if (id != null)
    {
        students = students
            .Where(s => s.SubgroupId == id).Where(s => s.GroupId == id);
    }

    ViewBag.result = students;
    return View(students.ToList());
}

组类:

public class Group
{
    public int Id { get; set; }
    public string Name { get; set; }
}

子组类:

public class Subgroup
{
    public int Id { get; set; }  
    public string Name { get; set; }
    [ForeignKey("GroupId")]
    public virtual Group Group { get; set; }
    public int? GroupId { get; set; }
}

学生班:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    [ForeignKey("GroupId")]
    public virtual Group Groups { get; set; }
    public int? GroupId { get; set; }
    [ForeignKey("SubgroupId")]
    public virtual Subgroup Subgroups { get; set; }
    public int? SubgroupId { get; set; }
}

当我删除 groupId 数据显示但组数据没有过滤所以所有组显示。

我不知道是什么错误

谢谢

【问题讨论】:

  • id参数,是组id还是子组id?
  • 两者都错了?
  • 你会包含你的模型类吗?
  • 我现在可以查看

标签: asp.net-mvc filter


【解决方案1】:

您过滤了两次,尝试过滤一次:

if (id != null)
{
    students = students
        .Where(s => s.SubgroupId == id && s.GroupId == id);
}

此外,如果在您的模型/应用程序中,Student 可以属于一个组和一个子组,其组与学生组不同(这很可能),那么您需要删除 Group 外键/属性来自Student 实体,因为您始终可以从Subgroup 属性访问Group

【讨论】:

  • 我得到这个错误 Error The name 's' does not exist in the current context Error Syntax error, ','
  • @programmer 再次检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
相关资源
最近更新 更多