ASP MVC 5如何在JSON NET的帮助下从请求中读取对象

时间:2016-08-13 21:31:12

标签: c# json asp.net-mvc

我需要使用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 call

$.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";
    }

我错过了什么或做错了什么?

1 个答案:

答案 0 :(得分:0)

更正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); 
        }
    });