1

当我使用 jquery ajax 处理请求时,我在控制器中得到空值

控制器

[HttpPost]
       public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
       {
           var replacetext=string.Empty;
           if (answers.Length>0) 
             replacetext = answers.Replace("\n", ",");
           _service.UpdateAnswers(eventid, replacetext, controlid);
           return PartialView("CustomizedQuestions");
        }

Jquery - Ajax 代码

 var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
                        $.ajax({
                            url: '@Url.Action("UpdateAnswers")',                                
                            type: 'POST',
                            dataType: 'html',
                            contentType: 'application/html; charset=utf-8',
                            context: $(this),
                            // data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
                             data: JSON.stringify(test),   
                            success: function (result) {
                                $(this).dialog("close");
                            },
                            error: function () {
                                //xhr, ajaxOptions, thrownError
                               alert('there was a problem saving the new answers, please try again');
                            }
                        });
4

1 回答 1

4

contentType错了。为什么application/html在传递 JSON 时设置为?试试这样:

var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
    url: '@Url.Action("UpdateAnswers")',                                
    type: 'POST',
    dataType: 'html',
    contentType: 'application/json; charset=utf-8',
    context: $(this),
    data: JSON.stringify(test),   
    success: function (result) {
        $(this).dialog("close");
    },
    error: function () {
        //xhr, ajaxOptions, thrownError
        alert('there was a problem saving the new answers, please try again');
    }
});

或使用application/x-www-form-urlencoded默认值:

var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
    url: '@Url.Action("UpdateAnswers")',                                
    type: 'POST',
    dataType: 'html',
    context: $(this),
    data: test,
    success: function (result) {
        $(this).dialog('close');
    },
    error: function () {
        //xhr, ajaxOptions, thrownError
        alert('there was a problem saving the new answers, please try again');
    }
});
于 2012-05-24T11:13:18.060 回答