在asp.net mvc 5中过滤viewbag元素

时间:2016-01-01 11:20:34

标签: asp.net-mvc-5

Action Controller:
public ActionResult UserList()
    {
       ApplicationDbContext db = new ApplicationDbContext();
        var applicationDbContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
        ViewBag.Names = from u in db.Users
                    from ur in u.Roles
                    join r in db.Roles on ur.RoleId equals r.Id
                    select new
                    {
                        //u.Id,
                        Name = u.UserName,
                        Role = r.Name,
                    };
         return View();
    }
View:
     @{

foreach (var Name in ViewBag.Names)
    {
        <tr>@Name</tr><br />

    }
    }
 Result In Browser:
                  { Name = accountant@healthcure.com, Role = Accountant }
              { Name = hasanaccountant@healthcure.com, Role = Accountant }
              { Name = assistant@healthcure.com, Role = Assistant }
              { Name = hasanassistant@healthcure.com, Role = Assistant }
              { Name = hasan@healthcure.com, Role = Doctor }
              { Name = doctor@healthcure.com, Role = Doctor }
              { Name = usman171@hotmail.com, Role = Doctor }

&#34;但我只需要那些数据,其中Role = Doctor.How我可以通过更改查询或过滤viewbag结果来做到这一点。我的主要目的是获取角色及相关用户&#34; < / p>

1 个答案:

答案 0 :(得分:0)

使用ViewModel,如下所示。在TestModel文件夹

中创建一个名为Models的视图模型
public class TestModel
{
  public string Name {get; set;}
  public string Role {get; set;}
}

使用该视图模型创建强类型视图,而不是创建匿名对象和ViewBag

public ActionResult UserList()
    {
       ApplicationDbContext db = new ApplicationDbContext();
        var applicationDbContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
        IEnumareble<TestModel> models = from u in db.Users
                                        from ur in u.Roles
                                        join r in db.Roles on ur.RoleId equals r.Id
                                          select new TestModel
                                            {
                                               Name = u.UserName,
                                               Role = r.Name,
                                            };

         return View(models);
    }

使用模型IEnumareble<TestModel>

创建强类型视图
@{Model = IEnumareble<TestModel>}
     @{
       foreach (TestModel Name in Model.Where(m => m.Role == "Doctor"))
       {
        <tr>@Name</tr><br />
       }
      }