I'm experiencing a weird issue when trying to return a simple JSON object from my controller. In firefox debug tools I am able to see the JSON returned just fine; however, in my javascript call back I get a undefined in my console.log(data)
The Post (View)
@{
string postAction = string.IsNullOrEmpty(Model._id) ? "AddCredential" : "EditCredential";
string title = string.IsNullOrEmpty(Model._id) ? "Add" : "Edit";
string onSuccessAction = "";
if (!string.IsNullOrEmpty(Model.CallerLccation))
{
onSuccessAction = "Credentials.finishAddingCredFromEditPage();";
}
else
{
onSuccessAction = "General.init();$.fancybox.close();";
}
}
<h3>@title Credential</h3>
@using (Ajax.BeginForm(postAction, new AjaxOptions { HttpMethod = "Post", OnSuccess = onSuccessAction, UpdateTargetId = "credentialList", InsertionMode = InsertionMode.Replace }))
{
The controller (no bugs here)
public ActionResult AddCredential(CredentialViewModel viewModel)
{
//.......................
if (!string.IsNullOrEmpty(viewModel.CallerLccation))
{
//location the new credential being edited from is different than the normal location _CredentialList.cshtml
return Json(new
{
callerLocation = viewModel.CallerLccation,
credentialsDict = (object)JsonConvert.SerializeObject(GetCredentials(), Formatting.None),
newName = viewModel.Name,
newKey = newDoc["id"]
});
}
return PartialView("_CredentialList", GetCredentialListViewModel());
}
The callback
finishAddingCredFromEditPage: function (data) {
//diff logic for diff places add credential is called from
//UNDEFINED HERE
console.log(data);
switch(data.callerLocation) {
case "edit":
//reload phone dict
allCredentials = data.credentialsDict;
//add option to all dropdowns on the edit page
$('.credentialDropdown').each(function(i) {
$(this).prepend("<option selected></option>")
.attr("value", data.newKey)
.text(data.newName);
});
//reset stuff
General.init();
$.fancybox.close();
break;
}
},
What I've tried
- Adding
JsonRequestBehavior.AllowGetto myreturn Json()statement - Adding a dummy div with the id = credentialList to see if it would be filled with JSON
- Removed the
UpdateTargetIdand theInsertionModeproperties
I thought perhaps under the hood MVC was sending the request expecting HTML due to the fact that there was an updateTargetId but that did not turn out to be the issue. I have checked the response from the server and the JSON is indeed there. I am not too sure what other steps to take to troubleshoot this problem.