aln447
aln447

Reputation: 1011

JSON to MVC Object from an Ajax Post

I have this json array-ish variable which gets values from a table:

var data = { "Model": [] };
$(".student-grade-data-row").each(function () {
    data.Model.push({
        'subjectId' : currentSubjectId,
        'studentId': $(this).attr('id'),
        'grade1' : $(this).find(".grade-select").val(),
        'mult' : $(this).find(".mult-select").val(),
        'subject': $(this).find(".topic-input").val(),
    });
});

It was made to resemble a MVC class called grade

public partial class grade
{
    public int id { get; set; } //auto-set
    public int subjectId { get; set; }
    public string studentId { get; set; }
    public int grade1 { get; set; }
    public int mult { get; set; }
    public string subject { get; set; }
    public System.DateTime date { get; set; } //auto-set
}

Now in the perfect world, I would like to have the values inside the data variable to be send into my controller like this:

$.ajax({
    url: '/Ajax/SendGrades',
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    success: function (dt) {
        console.log(dt);
    }
});

And there I could pick it up, and serialize it as a proper object list.

The problem isI cannot even get a glimpse of what really am I sending to the controller and how possibly could I link it to the object.

I tried making the function take an agrument of type List<grade> Model, but It would keep telling me the value is null.


I tried using some basic serialization but cant get it to work either. The code

public ActionResult SendGrades(JsonResult Model)
{
    List<grade> g = new List<grade>();
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(grade));
    g = (List<grade>)serializer.ReadObject(Model);
    return Content("Hi");
}

Gives me an error saying

Cannot convert from System.Web.Mvc.JsonResult to System.IO.Stream

What would be the proper way to do this so I could later safely store the values in my database?

I'm fairly new to this type of work so I apologize for any noob-ism. Any help would be great here.

Upvotes: 3

Views: 2951

Answers (3)

Umair Anwaar
Umair Anwaar

Reputation: 1138

Your Model should be like

public partial class grade
{
    public int id { get; set; } //auto-set
    public int subjectId { get; set; }
    public string studentId { get; set; }
    public int grade1 { get; set; }
    public int mult { get; set; }
    public string subject { get; set; }
    public System.DateTime date { get; set; } //auto-set
}

and when u send data to server assign data using data.Model cause u are setting value to Model

$.ajax({
    url: '/Ajax/SendGrades',
    type: "POST",
    data: data.Model, //try to change it in ur code first if not work use jquery.post
    contentType: "application/json; charset=utf-8",
    success: function (dt) {
    console.log(dt);
    }
});

or Use Jquery Post

$.post('/Ajax/SendGrades', data.Model,
       function(data){
        console.log(data);
       });

and In Controller

public ActionResult SendGrades(List<grade> Model)
{
      //then write your logic here
}

Upvotes: 0

Ahamed Subair Ali
Ahamed Subair Ali

Reputation: 41

you may try this. add one more class contains the list of grade as a property

class Models
{
    public List<grade> Model{get; set;}
}

and change your Method like this

public ActionResult SendGrades(Models models)
{
    List<grade> g = models.Model;
    //then write your logic here
}

Upvotes: 0

user3559349
user3559349

Reputation:

You ajax options needs to include

type: 'POST'

By default, its a GET which has no body, therefore setting contentType is pointless and the DefaultModelBinder will not use the JsonValueProvider (for a GET, the format of the data would have needed to be data: { [0]subjectId: value, [0]studentId: value, [1]subjectId: value, [0]studentId: value, ....etc } - i.e. indexed property names)

The full code needs to be

$.ajax({
    url: '/Ajax/SendGrades',
    type: 'POST', // add this
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    success: function (dt) {
        console.log(dt);
    }
});

And the controller method

public ActionResult SendGrades(List<grade> model)

Upvotes: 3

Related Questions