1

I am new at MVC programming. Currently working on VS2017. I am trying to post data from View in JSON String format to Controller. When checked at Jquery Console the data is there but at controller it is received as null.

This is my Jquery Ajax

$('#btnSave').click(function () {
            var Studentdata = { JsonStr: addStudent }
            console.log(JSON.stringify(Studentdata))
            $(this).val('Please wait...');
            $.ajax({
                url: '/Students/SaveStudents',
                type: "POST",
                data: JSON.stringify(Studentdata),
                dataType: "JSON",
                traditional: true,
                contentType: 'application/json;charset=utf - 8',
            }); });

This is the Json String which is shown on the console on Click of Save Button


{"JsonStr":[{"StudentId":"1","Name":"Pravin","Email":"pra@gmal.com"},{"StudentId":"2","Name":"ramesh","Email":"ram@ymail.com"},{"StudentId":"3","Name":"suresh","Email":"s@mail.com"},{"StudentId":"4","Name":"parvesh","Email":"peter@h.com"}]}

Below is how my controller action is:

        [HttpPost]
        public IActionResult SaveStudents(string JsonStr)
        {
              // conditions to be written
            return View();
        }

Please, help me to resolve it. I tried a lot.

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56

1 Answers1

0

You can try this way

Step 1. Make sure that you have Studentdata class in server side.

    [HttpPost]
    public IActionResult SaveStudents(List<Studentdata> JsonStr)
    {
          // conditions to be written
        return View();
    }

Step 2. Adjust format contentType: 'application/json; charset=utf-8'`, as well. I see that it contains unnecessary spaces.

BTW, This post is very useful.

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56