petko_stankoski
petko_stankoski

Reputation: 10723

Sending data from ajax to controller in C#

I'm creating an object in javascript with LocationId and id.

I have a class MyClass in C# with those two variables.

I have an ajax call which calls a method in my controller:

MyMethod(List<MyClass> myObject, int user_id)

I use:

traditional: true

in the ajax call.

The method gets called, myObject has the correct length, but LocationId and id are all 0. Why is this happening and how to solve it?

public class MyClass {
     public int LocationId {get; set;}
     public int id {get; set;}
}

Javascript:

var myArray = new Array();
var object = new {
    LocationId: 1;
    id: 2;
}
myArray.push(object);

Ajax:

$.ajax({
    type: "GET",
    url: "correctUrl",
    traditional: true,
    data: { user_id: 1, myObject: myArray}
});

Upvotes: 1

Views: 182

Answers (2)

LeftyX
LeftyX

Reputation: 35597

I agree with Alex. I would change your ajax call like this:

$.ajax({
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8;',
    url: "correctUrl",
    data: JSON.stringify( {user_id: 1, myObject: myArray} ),
    // traditional: true,
    error: function (req, status, error) {
        alert(error);
    }
});

I've removed traditional: true you don't need it here.
Changed the submission type to POST. It works better with serialized object.
I've transformed the submitted data with JSON.stringify

You can download json2.js here and find more info here.

I've changed your C# class this way:

public class MyClass
{
    public int LocationId { get; set; }
    public int id { get; set; }
}

[Serializable]
public class jSonObject
{
    public int user_id { get; set; }
    public List<MyClass> myObject { get; set; }
}

and your MVC action should look like this:

    [HttpPost]
    public ActionResult MyMethod(jSonObject myData)
    {
        ...
    }

Another thing I would suggest is to implement a JsonValueProviderFactory.
You can find lot of useful information here and here.

Upvotes: 0

Alex
Alex

Reputation: 7858

Your Javascript code to create the object is invalid. Try this:

var myArray = new Array();
var object = {       // No new
    LocationId: 1,   // , instead of ;
    id: 2
}
myArray.push(object);

By the way, you could shorten this to:

var myArray = [ { LocationId: 1, id: 2 } ];

Upvotes: 2

Related Questions