2

我正在尝试结合 Mike Brind 提供的两个教程。它们单独工作,但结合起来却没有,我相信这只是我需要做的一个简单的改变。

我想在多个页面上显示查询,但如果我更改搜索参数,我希望它更新。这是我的代码(使用 Mike 的书籍示例):

@{
    Page.Title = "Paging Books";
    Page.Header = "View Books";

    var pageSize = 3; 
    var totalPages = 0; 
    var count = 0;
    var page = UrlData[0].IsInt() ? UrlData[0].AsInt() : 1;
    var offset = (page -1) * pageSize;

    var db = Database.Open("Books");
    var sql = "Select Count(*) From Books " + 
           "Inner Join Authors on Books.AuthorId = Authors.AuthorId " + 
           "Inner Join Categories on Books.CategoryId = Categories.CategoryId";
    count = (int)db.QueryValue(sql);
    totalPages = count/pageSize;        
    if(count % pageSize > 0){
        totalPages += 1;
    }
    sql = "Select Title, ISBN, Description, FirstName, LastName, Category From Books " + 
           "Inner Join Authors on Books.AuthorId = Authors.AuthorId " + 
           "Inner Join Categories on Books.CategoryId = Categories.CategoryId " +
           "Order By BookId OFFSET @0 ROWS FETCH NEXT @1 ROWS  ONLY;";

    var result = db.Query(sql, offset, pageSize);

    var categories = db.Query("Select CategoryID, Category FROM Categories");
}

<form method="post" action="">
    Select Category:
    <select name="CategoryID">
        <option value="">-- View All Books --</option>
        @foreach(var c in categories){
            <option value="@c.CategoryId">@c.Category</option>
        }
    </select> <br />
    <input type="submit" name="Action" value="Select" />
</form>           

<p>Page @page of @totalPages</p>
@if(IsPost){
    foreach(var row in db.Query(sql, offset, pageSize, Request["CategoryID"])){
        <h2>@row.Title</h2>
        <p><strong>Author:</strong> @row.FirstName @row.LastName<br />
            <strong>ISBN:</strong> @row.ISBN <br/>
            <strong>Description:</strong> @row.Description <br />
            <strong>Category: </strong> @row.Category</p>
    }
}


@{
    for (var i = 1; i < totalPages + 1; i++){
        <a href="/Paging/@i">@i</a>
    }
}

此代码当前显示正确页面中的所有信息,但是当我更改 时Category,它不仅显示匹配的结果,它仍然显示所有类别。

4

1 回答 1

4

您的 asp 代码不完整。您只有 SQL 代码来返回完整的图书列表。它没有包含根据用户选择的类别进行过滤的语句。

在你做之前:

var sql = "Select Count(*) From Books " + 
       "Inner Join Authors on Books.AuthorId = Authors.AuthorId " + 
       "Inner Join Categories on Books.CategoryId = Categories.CategoryId";

您需要测试请求是否包含具有非空值的属性 CategoryID。如果不为空,则定义一个不同的 sql 来过滤类别。像这样:

if(!Request.QueryString["CategoryID"].IsEmpty() ) {
    var sql = "Select Count(*) From Books " + 
           "Inner Join Authors on Books.AuthorId = Authors.AuthorId " + 
           "Where Books.CategoryID=@0";
    count = (int)db.QueryValue(sql, Request.QueryString["CategoryID"])
}
else {
    var sql = "Select Count(*) From Books " + 
           "Inner Join Authors on Books.AuthorId = Authors.AuthorId "; // no need for 2nd inner join
    count = (int)db.QueryValue(sql);
}

第二条 sql 语句中也出现了同样的问题。与上述调整偏移量类似。

于 2013-04-10T19:49:36.860 回答