模型之间的关系是:X有很多Y;Y有很多Z:
class X
{
int Id { get; set; }
[JsonIgnore]
IList<Y> Y { get; set; }
}
class Y
{
int Id { get; set; }
X x { get; set; }
[JsonIgnore]
IList<Z> Z { get; set; }
}
class Z
{
int Id { get; set; }
Y y { get; set; }
}
public class YBinder : DefaultModelBinder
{
readonly IQuizRepository _quizRepository = DependencyResolver.Current.GetService<IQuizRepository>();
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var y = (Y)base.BindModel(controllerContext, bindingContext);
if (problem.Chapter != null)
{
y.X = _quizRepository.getX(y.X.Id);
}
return y;
}
}
public class ZBinder : DefaultModelBinder
{
readonly IQuizRepository _quizRepository = DependencyResolver.Current.GetService<IQuizRepository>();
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var z = (Z)base.BindModel(controllerContext, bindingContext);
if (z.Y != null)
{
z.Y = _quizRepository.getY(z.Y.Id);
}
return z;
}
}我的问题是网格X和Y被填充了,但是网格Z抛出了一个JsonSerializationException。下面是填充网格Z并抛出异常的操作:
public ContentResult Problems(JqInViewModel jqParams)
{
var problems = _quizRepository.Problems(jqParams.page - 1, jqParams.rows, jqParams.sidx, jqParams.sord == "asc");
var totalProblems = _quizRepository.TotalProblems(false);
return Content(JsonConvert.SerializeObject(new
{
page = jqParams.page,
records = totalProblems,
rows = problems,
total = Math.Ceiling(Convert.ToDouble(totalProblems) / jqParams.rows)
}, new CustomDateTimeConverter()), "application/json");
}问题出在JSON的某些地方;当我把[JsonIgnore]放在类Z中进行调试时,网格加载时不会出现异常,否则会给出Newtonsoft.Json.JsonSerializationException。
class Z
{
int Id { get; set; }
[JsonIgnore] // this removes exception but then I cant bind y in grid
Y y { get; set; }
}有人能帮我找出哪里出了问题吗?
发布于 2014-03-22 16:56:01
您的模型中有循环依赖关系,您不能仅仅因为JSON格式不支持就将这样的对象图序列化。你将不得不以这种方式重新考虑你的模型,这样循环依赖就会被打破。想一想您需要传递给视图的唯一信息是什么,然后将域模型扁平化为一个简单的视图模型。最后,将这个平面化的视图模型传递给视图。
https://stackoverflow.com/questions/22575473
复制相似问题