我使用jquery ajax调用控制器操作(请参阅下面的代码),执行操作后,引发了一个无效的Json错误。我注意到,它返回页面内容。为什么会这样。任何人都可以帮我解决这个问题吗?
控制器
[HttpGet]
public ActionResult ViewDetails(int id)
{
var eventsdetails = _service.GeteventByID(id);
return View("EventDetails",eventsdetails);
}
[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 RedirectToAction("ViewDetails", new { id = eventid });
}
Javascript
function dropdownlist(controlid, title, answers, eventid) {
var $answersreplaced = answers.replace( /\,/g , " \r");
var $deleteDialog = $('<div><textarea id="answerlist" rows="10" cols="50">' + $answersreplaced + '</textarea><div><div style="font-size:9px">(To change back to an open answer field, delete all choices above and save)</div>');
$deleteDialog.dialog({
resizable: false,
height: 280,
width: 350,
title: title + " - Edit Choices",
modal: true,
buttons: {
"Save": function () {
$.ajax({
type: 'POST',
url: '@Url.Action("UpdateAnswers")',
dataType: 'json',
data: { answers: $('#answerlist').val(),
question: title,
controlid: controlid,
eventid: eventid
},
success: function (result) {
$(this).dialog("close");
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
// alert('there was a problem saving the new answers, please try again');
}
});
},
Cancel: function () {
$(this).dialog("close");
}
}
});
};
答案 0 :(得分:1)
这是因为您没有从动作返回JsonResult,而是重定向到另一个动作,而该动作又返回一个ViewResult。
尝试这样的事情:
[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);
var eventsdetails = _service.GeteventByID(eventid);
return Json(eventdetails);
}
答案 1 :(得分:0)
您在AJAX请求和dataType: 'json'
控制器操作中指定UpdateAnswers
,return RedirectToAction
显然会重定向到ViewDetails操作,而后者又会返回一个视图,而视图又是HTML。所以这没有意义。
您必须从UpdateAnswers控制器操作返回Json,而不是重定向。