我正在按照Phil Haack的示例将jQuery Grid与ASP.NET MVC一起使用 。我有它的工作,它很好...除了一个小问题。当我使用ID以外的其他内容对列进行排序时,从服务器返回的JSON数据非常……好……错。这是我的Controller方法。
[HttpPost]
public ActionResult PeopleData(string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = repository.FindAllPeople().Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var people = repository.FindAllPeople()
.OrderBy(sidx + " " + sord)
.Skip(pageIndex * pageSize)
.Take(pageSize);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (
from person in people
select new
{
i = person.PersonID,
cell = new List<string> { SqlFunctions.StringConvert((double) person.PersonID), person.PersonName }
}
).ToArray()
};
return Json(jsonData);
}
当我在jsGrid表中按PersonID排序时,我会得到此数据(我只是使用当前ID的名称作为名称-例如1、1、2、2等)。
{"total":1,"page":1,"records":6,"rows":[{"i":1,"cell":[" 1","One"]},{"i":2,"cell":[" 2","Two"]},{"i":3,"cell":[" 3","Three"]},{"i":4,"cell":[" 4","Four"]},{"i":5,"cell":[" 5","Five"]},{"i":6,"cell":[" 6","Six"]}]}
但是,当我按PersonName排序时,每隔一行的顺序(ID与名称)就会翻转。因此,当我在表中显示它时,PersonName在ID列中,而ID在person列中。这是JSON结果。
{"total":1,"page":1,"records":6,"rows":[{"i":5,"cell":[" 5","Five"]},{"i":4,"cell":["Four"," 4"]},{"i":1,"cell":[" 1","One"]},{"i":6,"cell":["Six"," 6"]},{"i":3,"cell":[" 3","Three"]},{"i":2,"cell":["Two"," 2"]}]}
有人对我做错了什么会导致这种情况有任何见解吗?
更新资料
因此,我了解到正在发生的事情是我的数组值正在针对数组中的所有其他项进行翻转。例如...如果我用以下数据填充数据库:
[A,B,C]
然后对于每个偶数结果(如果从0开始计数,则为奇数),我的数据又回来了:
[C,B,A]
因此,最终,我的JSON行数据如下所示:
[A,B,C] [C,B,A] [A,B,C] [C,B,A] ...等等
这一直在发生并且始终如一。我有点发疯,试图弄清楚发生了什么,因为看起来应该很简单。
我在这里找到解决方案: LINQ到实体orderby奇怪的问题
问题最终归因于Linq to Entities在处理字符串方面遇到麻烦。当我使用SqlFunctions.StringConvert方法时,这错误地执行了转换(尽管我必须承认我不完全理解为什么随后要转换顺序)。
在上述两种情况下,无论哪种情况,解决此问题的解决方案都是在本地进行选择,以便我可以“强制” Linq to Entities正确使用字符串。由此,我的最终代码是:
var people = repository.FindAllPeople()
.OrderBy(sidx + " " + sord)
.Skip(pageIndex * pageSize)
.Take(pageSize);
// Due to a problem with Linq to Entities working with strings,
// all string work has to be done locally.
var local = people.AsEnumerable();
var rowData = local.Select(person => new
{
id = person.PersonID,
cell = new List<string> {
person.PersonID.ToString(),
person.PersonName
}
}
).ToArray();
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = rowData
};
return Json(jsonData);
我的数据是INT类型,我也遇到同样的问题。如果我的队列(A,B,C)中的元素是NVARCHAR类型,则不会出现此问题。因此,问题显然出在SqlFunction.StringConvert函数中。