0

我要做的是根据我的 MVC3 控制器中登录用户的角色过滤查询。我限制用户只有一个角色;任何用户都不能拥有多个角色。我有一些代码片段,但我不确定这是要走的路。如果有人可以帮助我实现我的目标

  string[] roles = Roles.GetRolesForUser();

    string color= roles[0];

    string vcolor = color.Substring(0, 4);

    switch (vcolor)
                {
                    case "Rewa":
                        vcolor = "white";
                        break;
                    case "Ukau":
                        vcolor == "black";
                        break;
                    case "Whau":
                        vcolor = "green";
                        break;
                    case "Angi":
                        vcolor = "Blue";
                        break;
                }

public ActionResult _MembersView()
    {
        var pagenew = db.Members

            .Where(u => u.color == vcolor)(I will want to then set this condition to the vcolor dynamically)
            .OrderBy(u => u.Tcd);
            //.Take(12);
        return PartialView(pagenew);

    }
4

1 回答 1

0

将您的逻辑放入一个方法中:

private string GetVColorForCurrentUser()
{
    string[] roles = Roles.GetRolesForUser();
    string color = roles[0];
    string vcolor = color.Substring(0, 4);
    switch (vcolor)
    {
        case "Rewa":
            return "white";
        case "Ukau":
            return "black";
        case "Whau":
            return "green";
        case "Angi":
            return "Blue";
    }
    return vcolor;
} 

然后调用这个方法:

public ActionResult _MembersView()
{
    var pagenew = db
        .Members
        .Where(u => u.color == GetVColorForCurrentUser())
        .OrderBy(u => u.Tcd);
    return PartialView(pagenew);
}

或者直接写成过滤方法:

private bool CurrentUserHasSameVColor(Member member)
{
    string[] roles = Roles.GetRolesForUser();
    string color = roles[0];
    string vcolor = color.Substring(0, 4);
    switch (vcolor)
    {
        case "Rewa":
            vcolor = "white";
            break;
        case "Ukau":
            vcolor = "black";
            break;
        case "Whau":
            vcolor = "green";
            break;
        case "Angi":
            vcolor = "Blue";
            break;
    }
    return member.color == vcolor;
}

接着:

public ActionResult _MembersView()
{
    var pagenew = db
        .Members
        .Where(CurrentUserHasSameVColor)
        .OrderBy(u => u.Tcd);
    return PartialView(pagenew);

}
于 2013-01-04T15:46:49.133 回答