C# mvc从数据库获取虚拟IEnumerable
我正在尝试将C# mvc从数据库获取虚拟IEnumerable,c#,asp.net-mvc,C#,Asp.net Mvc,我正在尝试将dropdownlistfor绑定到来自数据库的列表 在模型中 public class Actor { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] ... // I have a database table called genre [ForeignKey("Genre")] public virtual IEnumerable<Genre>
dropdownlistfor
绑定到来自数据库的列表
在模型中
public class Actor
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
...
// I have a database table called genre
[ForeignKey("Genre")]
public virtual IEnumerable<Genre> Genres { get; set; }
}
在视图中
<div class="form-group">
@Html.LabelFor(model => model.Genres, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="dropdown">
@Html.DropDownListFor(M => M.Genre, new SelectList(Model.Genres, "Value", "Text"))
</div>
</div>
</div>
@LabelFor(model=>model.Genres,htmlAttributes:new{@class=“controllabel col-md-2”})
@DropDownListFor(M=>M.Genre,新选择列表(Model.Genres,“Value”,“Text”))
我需要做什么
谢谢您应该为此创建ViewModel
public class ActorViewModel
{
public Actor actor { get; set; }
public SelectList Genres { get; set; }
public int GenreId { get; set; }
}
创建一个方法,以selectlist的形式返回流派
public SelectList GetAsSelectList()
{
var genres = (from s in GetAllGenres()
select new
{
s.Id, s.Name
}).ToList();
return new SelectList((IEnumerable)genres, "Id", "Name");
}
在控制器中,填充模型属性:
var model = new ActorViewModel
{
actor = new Actor(),
Genres = GetAsSelectList(),
GenreId = 0
};
return View(model);
他认为:
@Html.DropDownListFor(M => M.GenreId, Model.Genres,"--Select--")
我通常会在我的
ViewModel
中添加类型为IEnumerable
的属性:
然后设置为:
viewModel.Genres = this.GetGenres();
然后在我的视图中
@Html.DropDownListFor(m => m.GenreId, Model.Genres, "Please select")
public IEnumerable<SelectListItem> GetGenres()
{
foreach (var genre in dbContext.Genres)
{
yield return new SelectListItem
{
Value = genre.Id.ToString(),
Text = genre.Name
};
}
}
viewModel.Genres = this.GetGenres();
@Html.DropDownListFor(m => m.GenreId, Model.Genres, "Please select")