背景:
在视图中,我们要求(通过jquery和ajax)控制器来获取数据库中的数据。数据以Json的形式返回,但由于原因未知,Json对象的一部分返回为null,即使它在控制器的JsonResult中正确设置。
守则:
要作为JsonResult
返回的类public class InData
{
public InData() { }
public AppsWithActions[] apps { get; set; }
public User[] users { get; set; }
public string timePeriod { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string dataType { get; set; }
}
问题是javascript中的字符串数组actionIds和actionNames在javascript中为null,即使它们在JsonResult中具有正确的值:
public class AppsWithActions
{
public AppsWithActions() { }
public string id { get; set; }
public string name { get; set; }
public string[] actionIds { get; set; }
public string[] actionNames { get; set; }
}
控制器功能,用于设置InData并将其返回到javascript:
//Takes a goal setting, turns it to indata and returns a JsonResult
public JsonResult GetIndataFromGoalSettingId(SettingId settingId)
{
var id = ToGuid(settingId.idString);
GoalSetting setting = Session.Query<GoalSetting>()
.Where(x => x.Id == id)
.FirstOrDefault();
var indata = TransformGoalSettingToInData(setting);
return Json(new { returnvalue = indata }, JsonRequestBehavior.AllowGet);
}
ajax调用返回一切正确的,除了apps.actionIds和apps.actionNames
function getIndataFromGoalSettingId(settingId) {
if (settingId != null) {
settingIdIn = { "idString": settingId};
$.ajax({
type: "POST",
async: false,
traditional: true,
url: 'GetIndataFromGoalSettingId',
data: JSON.stringify(settingIdIn),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
//...
}
});
}
}
应该说我们已成功使用相同类型的基础设施获取数据并将其作为Json返回到javascript之前,但是如果有人有更好的建议,请随意拼出来!