从数据库中获取数据并从MVC </object>中的List <object>填充下拉列表

时间:2014-11-27 09:27:28

标签: c# asp.net linq asp.net-mvc-4 html.dropdownlistfor

我有模特:

public partial class UserRole
{
    public int ID { get; set; }
    public int UserID { get; set; }
    public int RoleID { get; set; }
    public int Status { get; set; }

    public virtual user Users { get; set; }
    public virtual Role Roles { get; set; }
}

public partial class user
{
    public user()
    {
        Roles = new List<SelectListItem>();
    }

    public long id { get; set; }
    public string email { get; set; }
    public string password { get; set; }
    public System.DateTime reg_date { get; set; }
    public byte validated { get; set; }
    public virtual ICollection<UserRole> UserRoles { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }

    public IEnumerable<SelectListItem> Roles { get; set; }

    //public IEnumerable<Role> Roles { get; set; }
}

public partial class Role
{
    public int ID { get; set; }
    public string RoleName { get; set; }
    public string Desc { get; set; }
    public int Status { get; set; }
    public virtual ICollection<UserRole> UserRoles { get; set; }
}

加载视图的控制器:

public ActionResult AssignRole(long id = 0)
    {
        user UserModel = new user();
        int UserId = Convert.ToInt32(id);
        IList<user> Users = new List<user>();
        var query = from Role in db.Roles
                    join UserRole in db.UserRoles on Role.ID equals UserRole.RoleID
                    join user in db.users on UserRole.UserID equals user.id
                    where UserRole.UserID == UserId
                    select new { RoleName  = Role.RoleName, email = user.email, UserId = user.id };



        var userss = query.ToList();
        foreach(var userList in userss)
        {
            Users.Add(new user()
                {
                    id = userList.UserId,
                    email = userList.email,
                    RoleName = userList.RoleName
                });
        }

        LoadRoles(Users);
        return View(Users);
    }

public void LoadRoles(IList<user> model)
    {

        var Roles = db.Roles.AsQueryable<Role>().Select(x => new SelectListItem()
        {

            Text = x.RoleName,
            Value = SqlFunctions.StringConvert((double) x.ID)
        }).ToList();

        var UserModel = new user()
        {
            Roles = Roles.ToList()
        };

    }

我可以在视图的第一部分从LINQ获取其他值,但无法填充下拉列表。

<fieldset>
<div>
    <table>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.email)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.RoleName)
            </th>
            <th></th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.email)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.RoleName)
                </td>
                <td>
                    @Html.ActionLink("Delete", "Delete", new { id = item.id })
                </td>
            </tr>
        }
    </table>
</div>

<div class="display-label">
    @Html.DisplayName("Add Role")
</div>

@foreach (var item in Model)
{
    <div class="display-field">
        @Html.DropDownListFor(modeIteml => item.RoleId, item.Roles)
    </div>
}

<p>
    <input type="submit" value="Assign" />
</p>

如何填充下拉列表?我已经尝试了很多,但仍然没有运气。

1 个答案:

答案 0 :(得分:0)

如果你这样写,你会发现它更清楚:

public ActionResult AssignRole(int id = 0)
{
    var user = (from u in db.users
               join r in db.UserRoles on r.UserId equals u.id into g
               where u.id == id
               select new user
               {
                   id = u.id,
                   email = u.email,
 // assign the properties like any normal select.
                   Roles = g.Select(x => new Role { RoleName = x.rolename ... })
               })
               .FirstOrDefault();

    return View(user); // Update your view to expect a single user
}

通过这种方式,您可以快速访问数据库,获得所需的一切,并且您的模型代表您所拥有的(具有多个角色的单个用户)。

如果您想要分配一个单独的角色列表,我建议为该场景添加单独的视图模型。即。

public class AssignRolesModel 
{
    public user User { get; set; }
    public IEnumerable<Role> AvailableRoles { get; set; }
}

然后将返回视图(用户)更改为:

var viewModel = new AssignRolesModel
               {
                   User = user,
                   Roles = db.Roles
                             .Select(x => 
                                new SelectListItem()
                                {
                                    Text = x.RoleName,
                                    Value = SqlFunctions.StringConvert((double) x.ID)
                                })
                             .ToList()
               };

return View(viewModel);