Asp.net MVC 4
Entity Framework 5
LINQ
C#
我有一个ViewModel我已经使用。我现在添加我的PermissionType模型到我的ViewModel。
该模型表示数据库中具有相同名称的表。
如何将此表转换为@Html.DropDownListFor()
从表的'text'我需要'name'从数据库。从表中的"值"中,我需要从数据库中获取"ID"。
我如何把这个模型变成一个可用的下拉列表从我的控制器到我的页面?
ForumBoard model = new ForumBoard();
model.TPGForumQuery = db.TPGForums;
model.ProPit_User = db.ProPit_User.Where(m => m.username == userName).FirstOrDefault();
model.TPGForumTopicQuery = db.TPGForumTopics;
// need help here
model.PermissionType = // a list of all of the permission in this table
编辑:public class ForumBoard
{
public ForumBoard()
{
this.ProPit_User = new ProPit_User();
this.TPGForum = new TPGForum();
this.PermissionType = new List<ListItem>();
}
List<ListItem> PermissionType { get; set; }
public virtual IEnumerable<TPGForum> TPGForumQuery { get; set; }
public virtual ProPit_User ProPit_User { get; set; }
public virtual IEnumerable<TPGForumTopic> TPGForumTopicQuery { get; set; }
public virtual TPGForum TPGForum { get; set; }
}
首先,更改视图模型
class ForumBoard
{
...
public IEnumerable<ListItem> PermissionType {get; set;}
...
}
然后赋值
ForumBoard model = new ForumBoard();
...
model.PermissionType = db.PermissionType
.Select(p=>
new ListItem (){ Text = p.FieldForText,
Value= p.FieldForValue });
编辑:如果您的字段是非字符串类型,不幸的是,您必须首先调用ToList()方法。
model.PermissionType = db.PermissionType
//.Select(p => new {Text = p.TextField, Value = p.permissionID })
.ToList()
.Select(p=> new ListItem (){
Text = p.Text.ToString(),
Value= p.Value.ToString()});
You can try this method :
//Controller :
using(MyContext context = new MyContext() )
{
IEnumerable<SelectListItem> listItems = context.PermissionType.Select( p => new SelectListItem{ Text = p.FieldNameFor , Value = p.FieldNameFor });
ViewBag.myList = listItems;
}
/*
Do other stuffs here and then return to View()
*/
// In your view :
@{
IIEnumerable<SelectListItem> listItems = (IEnumerable<SelectListItem>)ViewBag.myList;
}
@Html.DropDownListFor("Name of DropDownList" , listItems )