1

在 c# 控制器上编写用于分页的选择语句的正确方法是什么。这是我想出的最好的,但我知道它不起作用,因为它在网格的第一页上显示了所有数据......请帮助

public JsonResult getData(int start, int limit)
{
  List<MyItem> items = new List<MyItem>();
  using (SqlConnection con = new       SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices1"].ConnectionString))
 {
 SqlCommand cmd = con.CreateCommand();
 cmd.CommandText = "SELECT State, Capital FROM MYDBTABLE";
 con.Open();
 SqlDataReader reader = cmd.ExecuteReader();
 while (reader.Read())
 {
   MyItem item = new MyItem();
   item.State = reader[0].ToString(); 
   item.Capital = reader[1].ToString(); 
   items.Add(item);
 }
 con.Close();

 if ((start + limit) > Myitem.Count)
 {
    limit = Myitem.Count - start;
 }
 return Json(new {  myTable = items }, JsonRequestBehavior.AllowGet);
 }
}
4

3 回答 3

5

这是我喜欢用于分页的存储过程的模板。

CREATE PROCEDURE [dbo].[StoredProcName] 
    @page_size INT
    , @page_num INT
AS
BEGIN

    SET NOCOUNT ON;

    ; WITH RESULTS AS
    (
        SELECT *
            , ROW_NUMBER() OVER (ORDER BY <order_col> DESC) AS rn
            , ROW_NUMBER() OVER (ORDER BY <order_col> ASC) AS rn_reversed
        FROM <table>
    )
    SELECT *
        , CAST(rn + rn_reversed - 1 AS INT) AS total_rows
        , CAST(CASE (rn + rn_reversed - 1) % @page_size
            WHEN 0 THEN (rn + rn_reversed - 1) / @page_size
            ELSE ((rn + rn_reversed - 1) / @page_size) + 1 
            END AS INT) AS total_pages
    FROM RESULTS a
    WHERE a.rn BETWEEN 1 + ((@page_num - 1) * @page_size) AND @page_num * @page_size
    ORDER BY rn ASC 

END

你只需要传入存储过程page_sizepage_num你就可以开始了。

于 2012-11-20T21:48:33.107 回答
3

您可以使用 Linq 并使用Skip()Take()像这样:

public JsonResult getData(int page, int limit)
{
    DataTable dt = new DataTable();
    using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices1"].ConnectionString))
    {
        using (SqlCommand cmd = cnn.CreateCommand())
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT State, Capital FROM MYDBTABLE";
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                da.Fill(dt);
            }
        }
    }
    int start = (page * limit) - limit;
    List<MyItem> items  = (from DataRow row in dt.Rows
                           select new MyItem
                           {
                                State = row["State"].ToString(),
                                Capital = row["Capital"].ToString()
                           }).Skip(start - 1).Take(limit).ToList();
    return Json(new {  myTable = items }, JsonRequestBehavior.AllowGet);
}
于 2012-11-20T22:24:18.830 回答
0

我使用的基本模板是:

SELECT ROW_NUMBER(), <Rest of your columns>
FROM <Your Tables/Joins>
WHERE ROW_NUMBER() >= (@PageNum * @RowsPerPage)
AND ROW_NUMBER() < (@PageNum+1 * @RowsPerPage)
于 2012-11-20T22:16:42.877 回答