MAT14 MAT14 - 1 year ago 45
C# Question

Pass Class Type Parameter via ajax jquery

I have Class with following structure

public class MyType
{
[Key]
[Required]
public string name { get; set; }
[Key]
[Required]
public string type{ get; set; }

}


Public Class A
{
string Id{get;set;}
public List<MyType> aList{get;set;}
}


My ajax calling is following:

var listitem=[
{name:"a",type:1},
{name:"b",type:2},
{name:"c",type:3}
]

$.ajax({
url: '@Url.Action("ActionMethod", "Controller")',
type: 'post',
async: false,
data: {
Id: 1,
aList :listitem

},
success: function (resp) {

},
error: function (resp) {
}
});


My Action Method is following:

[HttpPost]
public ActionResult ActionMethod(A adata)
{
return some action;

}


I am getting value of Id in ActionMethod but list item is blank? how can i pass the list?

Answer Source

Try like this:

var adata = {
    Id: 1,
    aList: [
        { name: "a", type: 1 },
        { name: "b", type: 2 },
        { name: "c", type: 3 }
    ]
}

$.ajax({
    url: '@Url.Action("ActionMethod", "Controller")',
    type: 'post',
    data: JSON.stringify(adata),
    contentType: "application/json; charset=utf-8"
    success: function (resp) {

    },
    error: function (resp) {
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download