[英]Use viewmodel to bind data with html.dropdownlistFor in asp.net-MVC
I need to create @html.dropdownlistFor where data is coming from database. 我需要创建@ html.dropdownlistFor数据来自数据库。 I have modelView which combining two classes. 我有结合两个类的modelView。 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 { 公共类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).. 实现或是实现此目的的另一种更好的方法(在单个视图中显示来自类的模型数据和来自另一个类的下拉列表)。
@Html.DropDownList("Group", new SelectList(Model.Groups.Select(g => g.GroupName )))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.