MVC视图中下拉框的使用

首先要在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">&nbsp;&nbsp;片名:</label>
</div>
<div class="form-group">
@Html.TextBox("searchString", "", htmlAttributes: new { @class = "form-control", placeholder = "请输入片名" })
</div>
<input type="submit" value="查找" class="btn btn-primary" />
}

截图如下:

技术分享

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。