嗨,我已经开发了一个Mvc应用程序,该应用程序使用select语句从Sql服务器检索数据。我需要在数据表上实现服务器端分页和排序,我可以使用json检索数据并显示它。 这是一个非常简单的表,用于测试目的表,数据不是很大。
[HttpPost]
public ActionResult GetList()
{
int start = Convert.ToInt32(Request["start"]);
int length = Convert.ToInt32(Request["length"]);
string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][name]"];
string sortDirection = Request["order[0][dir]"];
List<YesNoModel> yesno = new List<YesNoModel>();
using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["TestApp"].ToString()))
{
YesNoModel yesNoMopdel = new YesNoModel();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select ynID,ynName FROM [Yes_No] WITH (NOLOCK)";
sqlCmd.Connection = sqlCon;
sqlCon.Open();
using (SqlDataReader sdr = sqlCmd.ExecuteReader())
{
while (sdr.Read())
{
yesno.Add(new YesNoModel
{
ynID = Convert.ToInt32(sdr["ynID"].ToString()),
ynName = sdr["ynName"].ToString(),
Action = "<a class='btn btn-info btn-xs' style='margin-top:6px' href='" + this.Url.Action("Edit", "YesNo", new { Id = Convert.ToInt32(sdr["ynID"].ToString()) }) + "'>Edit</a>" + "<a class='btn btn-danger btn-xs' style='margin-top:6px' onclick='return confirm()' href='" + this.Url.Action("Delete", "YesNo", new { Id = Convert.ToInt32(sdr["ynID"].ToString()) }) + "'>Delete</a>"
});
}
}
}
yesno.OrderBy(sortColumnName + " " + sortDirection);
yesno.Skip(start).Take(length);
return Json(new { data = yesno }, JsonRequestBehavior.AllowGet);
}
$('.table').DataTable({
"ajax": {
"url": "/YesNo/GetList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "ynID", "name": "ynID" },
{ "data": "ynName", "name": "ynName" },
{"data":"Action","name":"Action"}
],
"serverSide": "true",
"processing":"true",
"bDestroy": true
});
当我在调试模式下运行时单击排序时,我可以看到它正在选择正确的列并更改了排序方向,并且可以看到该表正在处理中,但实际上并没有改变顺序。谁能帮我。
答案 0 :(得分:0)
如果您认为OrderBy运作良好,请尝试
yesno = yesno.OrderBy(sortColumnName + " " + sortDirection).ToList();
它不起作用的原因是yesno。OrderBy(sortColumnName +“” + sortDirection)返回数组样式并生成新样式。
生成的一个和yesno(您定义的)完全不同