天天看點

Asp.net MVC3.0 入門指南 LIST

添加一個查找方法和查找視圖
在這一節我們将實作一個SearchIndex響應方法,允許您按流派或名字查找電影。
它利用網址/Movies/SearchIndex。請求将展示一個HTML頁面,它包含為了查
找電影由使用者輸入的input控件。當使用者送出頁面時,響應方法将獲得由使用者post
的查找條件并依據條件查詢資料庫。最終的效果圖如下所示 。
 
 
 
展示查找頁面
首先,在MoviesController類中添加一個SearchIndex響應方法。這個方法傳回一個包含HTML
頁面的視圖。代碼如下:
public ActionResult SearchIndex(string searchString)
{          
    var movies = from m in db.Movies
                 select m;
    if (!String.IsNullOrEmpty(searchString))
    {
        movies = movies.Where(s => s.Title.Contains(searchString));
    }
    return View(movies);
}
 
SearchIndex方法的第一行建立了以下的LINQ查詢來查詢電影:
var movies = from m in db.Movies
                 select m;
 
查詢在這裡定義,但卻沒有執行!(譯注:LINQ在需要執行的時候才會執行。
一般來說,真正需要使用資料時才真正執行)
 
如果參數searchString不是空字元串,電影的查詢被修改為過濾查找字元串,
使用如下代碼:
if (!String.IsNullOrEmpty(searchString))
    {
        movies = 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。
 
 
 
當您單擊Add按鈕時,視圖模闆ViewsMoviesSearchIndex.cshtml被建立。
因為您在架構模闆(Scaffold template)選擇List,Visual Studio自動在視 
圖中生成了一些内容。架建構立了一個HTML窗體。它檢查Movie類并為每個
類屬性建立代碼來輸出<label>元素。下面展示了自動生成的建立視圖:
@model IEnumerable<MvcMovie.Models.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 }) |