I am trying to create Product instance in Javascript and than to pass it to the server using [webmethod].
[WebMethod]
public static void SetProduct(Product product)
{
// i want a product instance
}
Following is Product class that i’m trying to create:
public class Product
{
public Type Type { get; set; }
public Foo Foo { get; set; }
public List<Bar> Bars { get; set; }
}
public class Type
{
public string ID { get; set; }
}
public class Foo
{
public string ID { get; set; }
public string Color { get; set; }
}
public class Bar
{
public string Name { get; set; }
}
I am being able to create Type and Foo but not List<Bar> in Javascript: (see my comments in the code for more details)
Javascript
function setProduct() {
var product = {};
product.Type = {};
product.Foo = {};
product.Type.ID = 'typeID';
product.Foo.ID = 'fooID';
product.Foo.Color = 'fooColor';
//here is my question how can create List<Bar> Bars and add it to product item???
$.ajax({
type: "POST",
url: "Default.aspx/SetProduct",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: "{product:" + JSON.stringify(product) + "}",
});
}
JavaScript doesn’t know what a
List<T>is. It only knows how to make arrays. So you’ll have to construct an array ofBars and pass that in the JSON.Fortunately, it’s an easy fix:
The above is probably all you need. I’m pretty sure ASP.NET will be smart enough to convert that
Bar[]into aList<Bar>automagically, but just in case it isn’t:Then if you still want
List<T>functionality, just convert the array to a List in your WebMethod:Now you can still access those nice
List<T>methods: