Reputation: 5075
I need to create @html.dropdownlistFor where data is coming from database. I have modelView which combining two classes. One for user and another one is Group. it suppose to show records of user in grid table along with drop down where group can be selected for that particular user.
public class UserGroup_ViewModel {
public List<User> Users { get; set; }
public List<Group> Groups { get; set; }
}
[Table("User")]
public class User
{
public User() { }
[Key]
public int UserID { get; set; }
[StringLength(250)]
[Required]
public string FirstName { get; set; }
[StringLength(250)]
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[StringLength(250)]
[Required]
public string EmailAddress { get; set; }
public ICollection<UserInGroup> UserInGroup { get; set; }
}
[Table("Group")]
public class Group
{
public Group() { }
[Key]
public int GroupID { get; set; }
[StringLength(250)]
[Required]
public string GroupName { get; set; }
public ICollection<UserInGroup> UserInGroup { get; set; }
}
public partial class UserManagement_Services
{
UserGroup_ViewModel _UserAndGroupModel = new UserGroup_ViewModel();
public UserGroup_ViewModel GetUserAndGroups()
{
using(var _uow = new UserManagement_UnitOfWork())
{
_UserAndGroupModel.Users = _uow.User_Repository.GetAll().ToList();
_UserAndGroupModel.Groups = _uow.Group_Repository.GetAll().ToList();
return _UserAndGroupModel;
}
}
}
public ActionResult AddUserInGroup()
{
var _UserAndGroupList = _userServices.GetUserAndGroups();
return PartialView("AddUserInGroup_Partial", _UserAndGroupList);
}
@model App.DAL.Model.UserGroup_ViewModel
<div>
<table class="table">
<tr>
<th>
@Html.DisplayName("First Name")
</th>
<th>
@Html.DisplayName("LastName")
</th>
<th>
@Html.DisplayName("Age")
</th>
<th>
@Html.DisplayName("EmailAddress")
</th>
<th></th>
</tr>
@foreach (var item in Model.Users)
{
<tr>
<td>
@Html.DisplayFor(modelItem => @item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
@Html.DropDownList(?????????????
<br/>
</td>
</tr>
}
</table>
data is access using generic repository pattern which return as following;
public IQueryable<TEntity> GetAll()
{
return _DbSet;
}
Am I on right track?? to achieve or is another better way to achieve this (show model data from class and dropdownlist from another class in single view)..
Upvotes: 1
Views: 1938
Reputation: 194
@Html.DropDownList("Group", new SelectList(Model.Groups.Select(g => g.GroupName )))
Upvotes: 1