//按电影类别来查询电影并排列
public ActionResult Index(string movieGenre, string searchString)
{
//可以放string类型的空的泛型集合
var Genrelst = new List<string>();
//下面的代码是从数据库中检索所有类型的LINQ 查询。
var GenreQry = from d in db.Movies
orderby d.Genre
select d.Genre;
//把不重复的电影类别放在集合的末尾
Genrelst.AddRange(GenreQry.Distinct());
//把查询的数据放到view.bag里
ViewBag.movieGenre = new SelectList(Genrelst);
//查询电影名称
var movies = from m in db.Movies
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s=>s.Title.Contains(searchString));
}
//通过类型查询电影。如何检查movieGenre参数。
//如果它不是空的代码进一步约束电影查询,以限制所选的电影到指定的类型
if (!String.IsNullOrEmpty(movieGenre))
{
movies = movies.Where(p=>p.Genre==movieGenre);
}
return View(movies);
}
视图里的代码
@model IEnumerable<Movies.Models.Movie>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
@*using的用法,还记得吗*@
@using (Html.BeginForm("Index", "Movies", FormMethod.Get))
//如果这样先执行控制器里的HttpGet方法。如果beginform没有参数执行Httppost方法
{
<p>电影名:@Html.TextBox("searchString")<br/>
类型:@Html.DropDownList("movieGenre", "全部类型")
<input type="submit" value="查询"/>
</p>
}
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.ActionLink("修改", "Edit", new { id=item.ID}) |
@Html.ActionLink("祥情", "Details", new { id=item.ID }) |
@Html.ActionLink("删除", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>