从数据库中获取数据并从 MVC 中的列表<对象>填充下拉列表

本文关键字:对象 填充 下拉列表 列表 MVC 数据库 获取 数据 | 更新日期: 2023-09-27 18:32:08

我有模型:

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>

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

从数据库中获取数据并从 MVC 中的列表<对象>填充下拉列表

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

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);