Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to return JsonResult

The following query is working successfully.

var tabs = (
                from r in db.TabMasters
                orderby r.colID
                select new { r.colID, r.FirstName, r.LastName })
                .Skip(rows * (page - 1)).Take(rows);

Now I want to return JsonResult as like

var jsonData = new
            {
                total = (int)Math.Ceiling((float)totalRecords / (float)rows),
                page = page,
                records = totalRecords,
                rows = (from r in tabs
                        select new { id = r.colID, cell = new string[] { r.FirstName, r.LastName } }).ToArray()
            };
return Json(jsonData, JsonRequestBehavior.AllowGet);

But it will gives me an error like: The array type 'System.String[]' cannot be initialized in a query result. Consider using 'System.Collections.Generic.List`1[System.String]' instead.

What should I do to get expected result?

like image 797
imdadhusen Avatar asked Jun 22 '11 05:06

imdadhusen


1 Answers

I suspect that it's as simple as pushing the last part into an in-process query using AsEnumerable():

var jsonData = new
{
    total = (int)Math.Ceiling((float)totalRecords / (float)rows),
    page = page,
    records = totalRecords,
    rows = (from r in tabs.AsEnumerable()
            select new { id = r.colID,
                         cell = new[] { r.FirstName, r.LastName } }
           ).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);

You may want to pull that query out of the anonymous type initializer, for clarity:

var rows = tabs.AsEnumerable()
               .Select(r => new { id = r.colID,
                                  cell = new[] { r.FirstName, r.LastName })
               .ToArray();

var jsonData = new { 
    total = (int)Math.Ceiling((float)totalRecords / (float)rows),
    page,
    records = totalRecords,
    rows
};
like image 177
Jon Skeet Avatar answered Oct 18 '22 04:10

Jon Skeet