I have 2 basic test applications where I do ajax requests. After calling the ajax request, for the first one, I need to parse the ajax data.responseText before retrieving the values. For the second one, I can access values directly.
Code of the first app:
@using (Ajax.BeginForm("JsonAdd", "People", new AjaxOptions { OnComplete = "JsonAdd_OnComplete" }))
{
...
}
function JsonAdd_OnComplete(data) {
var json = $.parseJSON(data.responseText);
if (json.Success) {
$("#PersonList").html(json.PartialViewHtml);
}
$("#addPersonModal").slideToggle();
$("#message").html(json.Message);
}
As you can see, I need to parse the data.responseText first before getting values.
Here is the second app:
@using (Ajax.BeginForm("_NewPersonToKeepInformed", "General", new { id = "NewPersonToKeepInformed" }, new AjaxOptions { Confirm = "Are you sure ?", HttpMethod = "POST", OnSuccess = "AddedSuccess" }))
function AddedSuccess(response) {
alert(response.message);
}
For this one, I cas access values directly.
UPDATE
Here is my controller action method:
public JsonResult JsonAdd(AddPersonViewModel AddPersonModel)
{
...
return Json(new
{
Success = true,
Message = "The person has been added!"
});
}
Here is the second one:
public JsonResult _NewPersonToKeepInformed(NewPersonToKeepInformedViewModel viewModel)
{
...
// return newly added person in a Json object
return Json(new { message = "Ajout effectué", firstName = viewModel.FirstName, lastName = viewModel.LastName, phone = viewModel.Phone, mail = viewModel.Mail });
}
Why?
Thanks.
In the first case you use the
OnCompleteand in the second you useOnSuccess. That’s the difference. They correspond to jQuery’scompleteandsuccesscallbacks. jQuery doesn’t parse the server’s response based on the Content-Type header inside thecompletecallback. That’s why you need to parse it manually. In thesuccesscallback this is done automatically. So if you want this to work for your first action replacenew AjaxOptions { OnComplete = "JsonAdd_OnComplete" }withnew AjaxOptions { OnSuccess = "JsonAdd_OnComplete" }