Linq to Javascript Array

1.1k views Asked by At

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
            }
        ]
    });
}
1

There are 1 answers

2
Aaron On BEST ANSWER

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.