【问题标题】:ASP MVC 5 How to read object from request with the help of JSON NETASP MVC 5 如何在 JSON NET 的帮助下从请求中读取对象
【发布时间】: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&lt;AbstractBuildBlock&gt;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


【解决方案1】:

正确的ajax调用

$.ajax({ 
        type: "POST",
        url: "/Site/Update",
        dataType: "json", 
        data: {JSON.stringify(filtersData) }, //without name because I'll use custom ModelBinder
        contentType: "application/json; charset=utf-8", 
        traditional: true,
        success: function (data) { 
            alert("ok"); 
        },
        error:function (xhr, ajaxOptions, thrownError) { 
            alert(xhr.status); 
            alert(thrownError); 
        }
    }); 

【讨论】:

    猜你喜欢
    • 2015-08-02
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多