3

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.

8
  • 1
    Change the method to public ActionResult SendGrades(List<grade> Model) (and always use url: 'Url.Action("SendGrades", "Ajax")', to generate the correct url). You also need to set contentType: "application/json; charset=utf-8", Commented Jan 23, 2017 at 4:51
  • This method, when tested claims to return empty variables. If I run return content(Model.First().subject) I'll get a NULL error. I'm using a separate js file to send values. Is this possible to use Url.Action? Commented Jan 23, 2017 at 4:56
  • Did you see the edited comment (regarding setting the contentType option)? Commented Jan 23, 2017 at 4:58
  • Yes. I'll edit the answer now Commented Jan 23, 2017 at 5:01
  • And you cannot use razor code in an external file, but you can pass it to the js file e.g. just use var url = '@Url.Action(..)'; to create a global variable in the main view, or use a data-url="@Url.Action(..)" to assign it in the element that triggers the ajax Commented Jan 23, 2017 at 5:01

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

1 Comment

Same error as for doing it the SendGrades(List<grade> Model) way
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.