【发布时间】:2016-08-13 21:31:11
【问题描述】:
我需要使用 JSON NET 序列化程序。
SiteModelBinder
internal class SiteModelBinder : System.Web.Mvc.IModelBinder
{
public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
{
// use Json.NET to deserialize the incoming Position
controllerContext.HttpContext.Request.InputStream.Position = 0; // see: http://stackoverflow.com/a/3468653/331281
Stream stream = controllerContext.RequestContext.HttpContext.Request.InputStream;
var readStream = new StreamReader(stream, Encoding.UTF8);
string json = readStream.ReadToEnd();
return JsonConvert.DeserializeObject<Site>(json, new JsonBuildBlockConverter());
}
}
在这里,我在位置 0,0 处得到一个无法识别的异常字符
return JsonConvert.DeserializeObject<Site>(json, new JsonBuildBlockConverter());
ajax 调用
$.ajax({
url: '/Site/Update',
data: { site: getSite() },
contentType: 'application/json',
method: 'POST',
success: function (data) {
console.log('Success save');
},
error: function (data) {
debugBox(data);
}
});
和 mvc 动作,BTW BuildBlocks 属性的类型是 List<AbstractBuildBlock> 和 TextBlock 是派生的。
public string Update(Site site)
{
//the goal to see in debugger that block is not null after the next line
TextBlock block = site.Pages[0].Rows[0].BuildBlocks[0] as TextBlock;
//siteRepository.Add(site);
return "Success";
}
我错过了什么或做错了什么?
【问题讨论】:
-
在抛出异常时你的字符串
json变量的值是多少? -
@darth_phoenixx site%5BsortedPages%5D%5B0%5D%5BsortedRows%5D=&site%5BsortedPages ...和这样的风格到最后
-
在创建 StreamReader 时,您指定 Encoding.UTF8 - 就msdn.microsoft.com/de-de/library/… 而言,BOM 是预期的。也许您的 ajax 调用以不同的编码发布数据。也许
new StreamReader(stream, true)有效。 -
我认为你的 ajax 帖子中应该有
dataType: 'json'。它把它作为序列化的表单数据传递,而不是通过它的外观。 -
@rboe 它不起作用(我尝试将 charset=utf-8 添加到 contentType,并使用 True 和 Encoding.UTF8 检查这两个变体都给出与开始时相同的结果。感谢您的评论。
标签: c# json asp.net-mvc