-1

I am new to javascript and having problems getting my head around a problem, that I am having. I have a list that I am trying to pass into a javascript file containing a datagrid called Grid.js.

How do I put a C# List into the correct format for javascript? Also how do I pass the js array from model to script?

controller:

Products = (from product context.Products
           select new project.Models.ProductsList
           {
               ProductID = Product.Id,
               Name = customer.Name,
               ProductNumber = customer.ProductNumber,
           }).ToList();

Format of DataSource for Grid(javascript).

var products= [{ "ProductID": 1, "Name": "Car", "ProductNumber": "AR-5381"},];

view

<table id="grid"></table><br />
<script type="text/javascript" src="../GridScript/ProductGrid.js">
    $(document).ready(myFunction());
</script>

Grid.js

var products = [];

$(myFunction() {
    $("#grid").igGrid({

        autoGenerateColumns: true,
        width: "80%",
        height: "600px",
        showHeaders: true,
        fixedHeaders: true,
        defaultColumnWidth: "200px",

        columns: [
            { headerText: "ProductID", key: "ProductID", dataType: "number" },
            { headerText: "Name", key: "Name", dataType: "string" },
            { headerText: "ProductNumber", key: "ProductNumber", dataType: "string" },
        ],

        dataSource: products,

        features: [
            {
                name: 'Paging',
                type: "local",
                pageSize: 25
            }
        ]
    });
}
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
Jimbo Jones
  • 983
  • 4
  • 13
  • 48
  • Could you include the declaration for `myFunction`? – recursive Nov 17 '14 at 21:46
  • `String myJSON = Newtonsoft.Json.JsonConvert.SerializeObject(Products)` will give you the object serialized as JSON. You may need to **nuget** the NewtonSoft library but trust me it's worth it. You'll still need to add the `var products = ...` to the client-side script, but that's just a detail. If you Google `JsonConvert.SerializeObject` you'll see plenty of references, though the first few I checked weren't terribly readable. – Ed Gibbs Nov 17 '14 at 21:47
  • Your question is common, how does one send LINQ enumerable to browser? The answer as posted is that you have to use JSON. I see you are using Jquery Igrid, I have no experience with that. – JWP Nov 17 '14 at 21:57

1 Answers1

2

Not sure if this is what your asking but I think you are looking for the JavaScriptSerializer class

Something Like:

var serializer = new JavaScriptSerializer();
            var serializedResult = serializer.Serialize(Products);

See The link for more details.

Aaron
  • 1,361
  • 1
  • 13
  • 30