Fork me on GitHub
听雨轩
生命易破碎,梦想只争朝夕!

添加一个查找方法和查找视图

在这一节我们将实现一个SearchIndex响应方法,允许您按流派或名字查找电影。它利用网址/Movies/SearchIndex。请求将展示一个HTML页面,它包含为了查找电影由用户输入的input控件。当用户提交页面时,响应方法将获得由用户post的查找条件并依据条件查询数据库。

展示查找页面

首先,在MoviesController类中添加一个SearchIndex响应方法。这个方法返回一个包含HTML页面的视图。代码如下:

public ActionResult SearchIndex(string searchString)
        {
            IEnumerable<MOVIE> movies = db.MOVIEs;
            if(!string.IsNullOrEmpty(searchString))
            {
               movies = db.MOVIEs.Where(s => s.TITLE.Contains(searchString));
            }

            return View(movies);
        }

SearchIndex方法的第一行创建了以下的LINQ查询来查询电影:

IEnumerable<MOVIE> movies = db.MOVIEs;

查询在这里定义,但却没有执行!( LINQ在需要执行的时候才会执行。一般来说,真正需要使用数据时才真正执行,叫做延迟加载)

如果参数searchString不是空字符串,电影的查询被修改为过滤查找字符串,使用如下代码:

if(!string.IsNullOrEmpty(searchString))
            {
               movies = db.MOVIEs.Where(s => s.TITLE.Contains(searchString));
            }

当定义或通过Where、OrderBy方法修改时,LINQ查询并没有执行。相反,查询的执行被延迟,这意味着LINQ表达式一直被延迟到它真实的值被遍历(循环)或被ToList方法调用。在SearchIndex方法中,LINQ查询在SearchIndex视图中执行。了解更多关于延迟查询执行,参见Query Execution

现在您可以实现SearchIndex视图展示给用户。右键SearchIndex方法内部并单击“Add View”,在“Add View”对话框中,指明您将传递Movie对象给视图模板作为它的模型类。在架构模板(Scaffold template)列表中,选择List,单击Add。

clip_image002

当您单击Add按钮时,视图模板Views\Movies\SearchIndex.cshtml被创建。

因为您在架构模板(Scaffold template)选择ListVisual Studio自动在视图中生成了一些内容。架构创建了一个HTML窗体。它检查Movie类并为每个类属性创建代码来输出<label>元素。下面展示了自动生成的创建视图:

@model IEnumerable<MvcMovie.DAL.MOVIE>

@{
    ViewBag.Title = "SearchIndex";
}

<h2>SearchIndex</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            TITLE
        </th>
        <th>
            RELEASEDATE
        </th>
        <th>
            GENRE
        </th>
        <th>
            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", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

运行程序,并导航到/Movies/SearchIndex。给URL追加一个查询字符串,比如

?searchString=ghost。筛选后的电影显示如下。

clip_image002

如果您改变SearchIndex方法的签名,改为一个名叫id的参数,id参数会匹配默认路由{id}占位符集合(在Global.asax文件中)。

{controller}/{action}/{id}

修改后的SearchIndex方法看起来如下所示:

public ActionResult SearchIndex(string id)
        {
            var searchString = id;
            IEnumerable<MOVIE> movies = db.MOVIEs;
            if(!string.IsNullOrEmpty(searchString))
            {
               movies = db.MOVIEs.Where(s => s.TITLE.Contains(searchString));
            }

            return View(movies);
        }

您现在可以使用路由数据(一个URL片段)来传递查找标题,而不是作为一个查询字符串了。(注意和上一个张图比较,看看URL发生了什么变化!)

clip_image002[4]

但是,您不能期望用户每次查找电影都来修改URL!所以现在您需要添加UI来帮助他们筛选电影。刚才您能改变SearchIndex的签名来测试如何传递路由绑定参数ID,现在把它改回原样。(刚才只是为了说明默认路由的作用)

public ActionResult SearchIndex(string searchString)
        {
            IEnumerable<MOVIE> movies = db.MOVIEs;
            if(!string.IsNullOrEmpty(searchString))
            {
               movies = db.MOVIEs.Where(s => s.TITLE.Contains(searchString));
            }

            return View(movies);
        }

打开文件Views\Movies\SearchIndex.cshtml,并在@Html.ActionLink("Create New", "Create")后添加如下代码:

@using (Html.BeginForm())
   { 
       <p>
           Title:@Html.TextBox("SearchString")<br />
           <input type="submit" value="Filter" />
       </p>
   
   }

下面的例子展示了Views\Movies\SearchIndex.cshtml文件的一部分标记。

@model IEnumerable<MvcMovie.DAL.MOVIE>
@{
    ViewBag.Title = "SearchIndex";
}
<h2>
    SearchIndex</h2>
    @Html.ActionLink("Create New", "Create")
    @using (Html.BeginForm())
    { 
        <p>
            Title:@Html.TextBox("SearchString")<br />
            <input type="submit" value="Filter" />
        </p>
    
    }

Html.BeginForm助手创建了一个开放的<form>标签。Html.BeginForm助手使得当用户单击Filter按钮时提交表单内的数据。运行程序并试着查找电影。

clip_image002[6]

8.13给页面添加分页功能

首先添加MvcPager.dll引用(MvcPager.dll是封装的一个分页程序集,文章结尾有下载),然后修改如下代码:

public ActionResult SearchIndex(string searchString, int page = 1)
       {
           IEnumerable<MOVIE> movies = db.MOVIEs;
           if (!string.IsNullOrEmpty(searchString))
           {
               movies = db.MOVIEs.Where(s => s.TITLE.Contains(searchString));
           }

           return View(movies.OrderBy(m => m.ID).ToPagedList(page, 1));
       }

修改SearchIndex.cshtml如下所示:

@using MvcPager;
@model PagedList<MvcMovie.DAL.MOVIE>
@{
    ViewBag.Title = "SearchIndex";
}
<h2>
    SearchIndex
</h2>
<style type="text/css">
    .pages
    {
        color: red;
        font-size: 11px;
        font-weight: bold;
        height: 40px;
        padding-top: 5px;
    }
    
    .pages .item
    {
        font-size: 13px;
        height: 20px;
        padding: 2px 6px;
    }
    
    .pages .cpb
    {
        color: red;
        font-size: 13px;
        padding: 1px 6px;
    }
    
    .pages a
    {
        border: 1px solid #DDDDDD;
        color: #000000;
        font-weight: normal;
        margin: 1pt 2px;
        padding: 0pt 5px;
        text-decoration: none;
    }
    
    .pages a:hover
    {
        background-color: #E61636;
        border: 1px solid #E61636;
        color: #FFFFFF;
        font-weight: normal;
        text-decoration: none;
    }
</style>
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm())
{ 
    <p>
        Title:@Html.TextBox("SearchString")<br />
        <input type="submit" value="Filter" />
    </p>
    
}
<table>
    <tr>
        <th>
            TITLE
        </th>
        <th>
            RELEASEDATE
        </th>
        <th>
            GENRE
        </th>
        <th>
            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", "Edit", new { id = item.ID }) |
                @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.ID })
            </td>
        </tr>
    }
</table>
@Html.Pager(Model, new PagerOptions { PageIndexParameterName = "page", CurrentPagerItemWrapperFormatString = "<span class=\"cpb\">{0}</span>", NumericPagerItemWrapperFormatString = "<span class=\"item\">{0}</span>", CssClass = "pages", SeparatorHtml = "", ShowPageIndexBox = false, PageIndexBoxType = PageIndexBoxType.DropDownList, ShowGoButton = false })

注意,如果View中找不到程序集的引用,需要手动添加引用,如:@using MvcPager;

运行结果如下:

clip_image002[5]

分页DLL下载:https://files.cnblogs.com/yuananyun/MvcPager.rar

posted on 2011-08-13 17:04  流水殇  阅读(3350)  评论(11编辑  收藏  举报