mesut
mesut

Reputation: 2177

Sending a JSON post request to asp.net mvc and getting partial view result, fails to get response

I'm working on a test application, I try to send question Id, and ans Id of a finished test to server, to calculate the results.

This is my JQuery function:

$('#finishTest').on('click', function () {
    //Post Back results
    var $answers_li = $('ol.answers li');

    var jsonObj = { Results: []};

    for(var i = 0; i < $answers_li.length; i++)
    {
        var questionNo = $($answers_li[i]).data("question-id");

        var answer = $('input:checked', $answers_li[i]);
        jsonObj.Results[i] = { QId: questionNo, AnsId: answer.val() };
    }

    //NOW I have my Json Object I must call a function on server to calculate results and sends us the results page
    var $url = $(this).data('url');
    $.ajax({
            url: $url,
            contentType: 'application/json',
            dataType: 'json',
            type: 'POST',
            data: JSON.stringify(jsonObj),
            complete: function (data) {                    
                $('section#TestWrapper').html(data);
            },
            error: function (xhr, data) {
                alert('failed');
            }
    });
});

And this is My Function On Serverside: Asp.net MVC

public ActionResult FinishTest(int Id, TestResultViewModel Answers)
    {

        TestResultViewModel model;

        if (Request.IsAjaxRequest())
        {
            //prepare Model;          
        }
        else
        {
            return HttpNotFound();
        }

        return PartialView("_TestResult", model);
    }

This is TestResultViewModel class definition:

 public class TestResultViewModel
{
    public IList<QAModel> Results { get; set; }

    //Other Useful Properties
}

public class QAModel
{
    public int QId { get; set; }

    public int AnsId { get; set; }
}

And Here is the response I get From My request but jquery say: parseerror for retrieved data.

Response Headers: 
Cache-Control:private, s-maxage=0
Content-Encoding:gzip
Content-Length:799
Content-Type:text/html; charset=utf-8
Date:Wed, 20 Aug 2014 08:54:29 GMT
Server:Microsoft-IIS/8.0
Vary:Accept-Encoding
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:5.2
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RTpcU2luYXZLdXJkdVxTaW5hdkt1cmR1XFNpbmF2a3VyZHUuV2ViVUlcU2luYXZrdXJkdS5XZWJVSS5Gcm9udEVuZFxUZXN0XEZpbmlzaFRlc3RcNA==?=

Request Headers:

Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,tr;q=0.6
Connection:keep-alive
Content-Length:323
Content-Type:application/json
Cookie:__RequestVerificationToken=Yv5fusfyb8EV5le8KOv6YPHIahIHkfvsF2mpnjU6oZ2Z1Ro_c60tvI6-JrDh7PJ6dTUGMavDCI-Y1BUm2rAUdyr4UnbjOKGwXOSqZqjNoag1; .AspNet.ApplicationCookie=5PJkE69hCjY8IsOP46Mm_jjR6yYvuQFVcsB3sQbC03xmnPqzPb-_gZNFm5tvKiCqSZzF6twHZX2aLe_NI6AAbDqZdBQL3t1gXZOtVvrQdY-v2r9Trvyys0AFjJH8zKhCQ7Uvz2fDONrLTpqWA9W9d1bssYSmhuZJkIY5SeaOXC8UO0wpWYYAo62zjzntl6DVWnWFaFR1aAXYmNTSjrqUyUFZ8VrVsG1mcDJAkSyIHpQ4mMAapS54VZQoo-x04xamLl93a_3wE9o9U5P3wmdknYzgYP-ay7I3VMRevGlG_vhpikH13ZenWLmeNdUJ4-1VJJOHy1lBYnmfurSpE1yNZTlsAO3q8XAROo6iKfnQm1KhmJmYzDWKo8R9Yi6KD0EpLA935y43MzIoN9vNhbvLuSKxTA222LbqmrmSKXwRTkReGnXR5HI2kDuZ9HNT0mbA1ltYhkueYBvHfyot_Gckcur2EaGbB_b-yszRPwnqJ7mZ3QstcWOtaKX0KFxvhD8Z-r2T9pD6wJzOLsQnnHB_2w
Host:localhost:2988
Origin:http://localhost:2988
Referer:http://localhost:2988/Test/Index/4
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
X-Requested-With:XMLHttpRequest

Upvotes: 0

Views: 958

Answers (2)

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

You are sending request to server and expecting a response in JSON but you are returing a PartialView.You need to return data in JSON format not the PartialView.Try this

public JsonResult FinishTest(int Id, TestResultViewModel Answers)
{

    TestResultViewModel model;

    if (Request.IsAjaxRequest())
    {
        //prepare Model;          
    }
    else
    {
        return HttpNotFound();
    }

    return Json(model);
}

Upvotes: 0

SSA
SSA

Reputation: 5493

You are expecting json in ajax call, but response is text/html.

From your response header.

Content-Type:text/html; charset=utf-8

remove dataType from ajax request and try.

$.ajax({
            url: $url,
            contentType: 'application/json',
            /*dataType: 'json',*/
            type: 'POST',
            data: JSON.stringify(jsonObj),
            complete: function (data) {                    
                $('section#TestWrapper').html(data);
            },
            error: function (xhr, data) {
                alert('failed');
            }
    });

From jquery documentation:

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.

Upvotes: 1

Related Questions