简体   繁体   中英

Fetching data from database and populating a dropdownlist from a List<object> in MVC

I have model:

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

Controller to load the view:

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

    }

I am able to get other values from the LINQ in the first part of view but unable to populate the dropdownlist.

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

How can I populate the dropdownlist? I have tried so much but still no luck.

You'll find it clearer if you write it like this:

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
}

This way you've gotten everything you need in one quick trip to the database, and your model represents what you have (a single user with multiple roles).

If you want a separate list of roles you can assign, I recommend putting in a separate view model for that scenario. ie

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

Then change return View(user) to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM