简体   繁体   English

将JSON发布请求发送到asp.net mvc并获得部分视图结果,无法获得响应

[英]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. 我正在开发一个测试应用程序,我尝试将问题ID和已完成测试的ans ID发送到服务器,以计算结果。

This is my JQuery function: 这是我的JQuery函数:

$('#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 这是我在服务器端的功能: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: 这是TestResultViewModel类的定义:

 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. 这是我从我的请求中得到的响应,但jquery表示:parseerror检索数据。

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

You are expecting json in ajax call, but response is text/html. 您期望在ajax调用中使用json,但响应为text / html。

From your response header. 从您的响应标题。

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

remove dataType from ajax request and try. 从ajax请求中删除dataType并尝试。

$.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: 从jQuery文档:

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.

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 您正在向服务器发送请求并期望以JSON响应,但是您正在重现PartialView。您需要以JSON格式而不是PartialView返回数据。

public JsonResult FinishTest(int Id, TestResultViewModel Answers)
{

    TestResultViewModel model;

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

    return Json(model);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM