user1930845
user1930845

Reputation:

Manually creating JSON data

I have this following code:

public ActionResult AjaxHandler(jQueryDataTableParamModel param)
{

    /* PROBLEM */
    var allCompanies = DataRepository.GetCompanies();
    /* PROBLEM */

    var result = from c in allCompanies
        select new[] { c.Name, c.Address, c.Town };

    return Json(new { sEcho = param.sEcho,
                     iTotalRecords = allCompanies.Count(),
                     iTotalDisplayRecords = allCompanies.Count(),
                     aaData = result
        },
                JsonRequestBehavior.AllowGet);
}

I NEED HELP WRITING

DataRepositry.GetCompanies();

The part that is marked as PROBLEM can someone help me write a function that returns data that will fit right in to make the code run. I know it suppose to be some kind of Json. But I can't figure out how to make it work.

DataRepository.GetCompanies() <- could be any function, I just need to make it work

I tried to do this:

      var allCompanies = new List<string[]>() {
                new string[] {"1", "Microsoft", "Redmond", "USA"},
                new string[] {"2", "Google", "Mountain View", "USA"},
                new string[] {"3", "Gowi", "Pancevo", "Serbia"}
                };

        var newJson = JsonConvert.SerializeObject(allCompanies);

        var allCompanies = newJson;

That did NOT work.

EXPLANATION:

This is part of a bigger project basically it suppose to populate DataTable, the exact error I am getting. Here is a screen attached.

Upvotes: 0

Views: 227

Answers (1)

Icarus
Icarus

Reputation: 63966

Try creating AllCompanies like so:

var allCompanies = new[]  { 
  new { Name="XYZ", Country="USA", ID="1"  },
  new { Name="ABC", Country="USA", ID="2"  }, 
  new { Name="DEF", Country="MX",  ID="3"  }
  };

My guess is that by not having property names and instead having a bunch of strings, there's no way to generate a proper JSON object with {key:value} pairs

Even better, create a Company class like so:

public class Company
{
   public string Name;
   public string Country;
   public string ID;
}

Upvotes: 1

Related Questions