小编典典

ASP.NET MVC如何将JSON对象从View传递到Controller作为参数

json

我有一个复杂的JSON对象,该对象没有任何问题即可发送到View(如下所示),但是当通过AJAX调用将数据序列化回.NET对象时,我无法弄清楚如何将该数据序列化回.NET对象。各个部分的详细信息如下。

   var ObjectA = {
        "Name": 1,
        "Starting": new Date(1221644506800),

        "Timeline": [
            {
                "StartTime": new Date(1221644506800),
                "GoesFor": 200

            }
            ,
            {
                "StartTime": new Date(1221644506800),
                "GoesFor": 100

            }

        ]
    };

我不确定如何将该对象传递给Controller方法,下面有此方法,其中Timelines对象使用Properties镜像上述JS对象。

public JsonResult Save(Timelines person)

我正在使用的jQuery是:

        var encoded = $.toJSON(SessionSchedule);

        $.ajax({
            url: "/Timeline/Save",
            type: "POST",
            dataType: 'json',
            data: encoded,
            contentType: "application/json; charset=utf-8",
            beforeSend: function() { $("#saveStatus").html("Saving").show(); },
            success: function(result) {
                alert(result.Result);
                $("#saveStatus").html(result.Result).show();
            }
        });

我还看到了使用’JsonFilter’手动反序列化JSON的参考,但是我想知道是否有一种方法可以通过ASP.NET
MVC来实现。或以这种方式传递数据的最佳实践是什么?


阅读 487

收藏
2020-07-27

共1个答案

小编典典

编辑:

随着MVC 3的到来,不再需要这种方法,因为它将自动处理-http:
//weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3
-preview-1.aspx


您可以使用以下ObjectFilter:

    public class ObjectFilter : ActionFilterAttribute {

    public string Param { get; set; }
    public Type RootType { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
            object o =
            new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
            filterContext.ActionParameters[Param] = o;
        }

    }
}

然后可以将其应用于您的控制器方法,如下所示:

    [ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
    public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }

因此,基本上,如果帖子的内容类型是“ application / json”,则它将生效,并将值映射到您指定的类型的对象。

2020-07-27