首先要在controller 中将选项设置成 selecList对象,并赋值给viewBag动态对象。
public ActionResult Index(string movieGenre,string searchString)
{
var GenreLst = new List<string>();
var GenreQry = from d in db.Movies
orderby d.Genre
select d.Genre;
GenreLst.AddRange(GenreQry.Distinct());
ViewBag.movieGenre = new SelectList(GenreLst);
var movies = from m in db.Movies
select m;
if (!string.IsNullOrWhiteSpace(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
if (!string.IsNullOrWhiteSpace(movieGenre))
{
movies = movies.Where(x => x.Genre == movieGenre);
}
return View(movies.ToList());
}
在View中有两种用法
1、@Html.DropDownList("movieGenre", "All") name=movieGenre, 自动读取viewBag.movieGenre 数据,第二个参数下拉框是第一行显示的数据。
2、 @Html.DropDownList("movieGenre", ViewBag.movieGenre as SelectList,"全部", new { @class="form-control"})
@using (Html.BeginForm("Index", "Movie", FormMethod.Get, htmlAttributes: new { @class = "form-inline", role = "form" }))
{
<div class="form-group">
<label class="control-label" for="movieGenre">类别:</label>
</div>
<div class="form-group">
@Html.DropDownList("movieGenre", ViewBag.movieGenre as SelectList,"全部", new { @class="form-control"})
</div>
<div class="form-group">
<label for="searchString" class="control-label"> 片名:</label>
</div>
<div class="form-group">
@Html.TextBox("searchString", "", htmlAttributes: new { @class = "form-control", placeholder = "请输入片名" })
</div>
<input type="submit" value="查找" class="btn btn-primary" />
}
截图如下: