在ASP.Net MVC3中使用Html.DropDownListFor助手时,填充SelectList的正确方法是什么?
我基本上有一个"Create“表单,我想在这个表单上指定特定字段的输入值。例如,它是一个电影数据库,我希望能够输入类型,但我不希望用户能够输入他们喜欢的内容,所以我假设SelectList是最好的答案?
一种可行的方法是使用静态方法创建一个新类来返回SelectList:
public class Genres
{
public static List<string> GetGenres()
{
List<string> myGenres = new List<string>();
myGenres.Add("Comedy");
myGenres.Add("Romantic Comedy");
myGenres.Add("Sci-Fi");
myGenres.Add("Horror");
return myGenres;
}
}然后可以像这样使用它:
<div class="editor-field">
@Html.DropDownListFor(model => model.Genre, new SelectList(OLL.Models.Genres.GetGenres()))
</div>这似乎不是最正确/最简单的方法?我想我遗漏了一些明显的东西...
感谢您所能提供的任何帮助。
发布于 2011-11-25 13:22:52
这是一个简单的selectList风格,我一直用来做下拉菜单,希望你能发现这一点。
ViewBag.AlbumListDD = from c in db.Query<DatabaseEntities.VenuePhotoAlbum>("WHERE VenueId = @0", VenueId)
select new SelectListItem
{
Text = c.Name,
Value = c.Id.ToString()
};在我的视图中:
@Html.DropDownList("AlbumId", (IEnumerable<SelectListItem>)ViewBag.AlbumListDD, new { id = "ChangeAlbum" })希望您能发现这一点很有用,因为这是一条数据库路径。我通常喜欢将所有这类信息放在一个数据库中,这样用户就可以动态地添加/删除和更改这些下拉项。删除类型时需要在幕后执行一些SQL工作,但在这一点上对我来说已经被证明是非常成功和快速的。
发布于 2013-10-19 22:00:41
var og = (from s in DB.Products
select new SelectListItem
{
Text = s.ProductName,
Value = s.ProductID.ToString()
});
ViewBag.lstProducts = new SelectList(getproductname, "ProductID", "ProductName");
<p>
@Html.DropDownList("AlbumId", (IEnumerable<SelectListItem>)ViewBag.lstProducts, new { @id = "drp" });
</p>https://stackoverflow.com/questions/5885627
复制相似问题