繁体   English   中英

jQuery JSON将对象保存到ASP.NET MVC2

[英]jQuery JSON save object to ASP.NET MVC2

我正在使用ASP.NET MVC2和jQuery来加载和保存对象。 我正在使用knockout.js的对象serilization /反序列化来在加载/保存数据时安全地维护对象的数据结构。

当我使用以下JavaScript方法将我的对象以其确切的结构发送回服务器时,在ASP.NET的服务器端,我的GraduationClass对象被实例化,但它没有任何数据。

我检查了firebug中的post数据,所有数据都正确地以正确的结构发送回请求中的服务器,但ASP.NET MVC内部管道无法将数据反序列化回GraduationClass对象。 我在使用和不使用contentType设置时尝试了这个。

我想知道我做错了什么。

// javascript save method
function save(graduationClass) {
    $.ajax({
        url: "/SiteManagement/saveGraduationClass",
        type: "POST",
        // data: ko.mapping.toJSON(graduationClass), // (solution 1)
        data: graduationClass, // (solution 2)
        contentType: "application/json; charset=utf-8",
        dataType: "json",            
        success: function(data) {            
    });    
}

// both solutions result in a blank object construction on the server side

// ASP.NET MVC2 AJAX method
[HttpPost]               
public ActionResult saveGraduationClass(GraduationClass graduationClass) {
    // graduationClass here has all default data rather than the data sent in the post
    return Json(new { resultText = "success" }, JsonRequestBehavior.AllowGet);
}

我相信有两个可能的问题。

首先,我非常确定当您指定在Ajax请求中发送JSON时,jQuery将序列化在数据参数中传递的Javascript对象。 你肯定是创建一个jQuery对象,其属性json的值为字符串(我相信,我不熟悉淘汰赛)。 传递给MVC的值如下所示:

{
  json : 'string of graduationClass data '
}

哪种是双序列化。

第二个问题是,以前的JSON不符合您的saveGraduationClass方法参数graduationClass

我认为这些解决方案都应该有效:

data: ko.toJSON(graduationClass),  // knockout.js utility method

要么

data: graduationClass,  // let jQuery serialize the object.

更新

如果我有这个课程:

public class Person
{
  public string Name { get; set; } 
}

我有这个JSON:

{
  Name : 'Jon Doe'
}

然后它将填充此方法:

public ActionResult SomeMethod(Person person)

但是,以下JSON将不起作用:

{
  json : '{ Name : "Jon Doe" }'
}

它也不匹配:

{
  json :
  {
    Name : 'Jon Doe'
  }
}

JSON的布局需要与尝试填充的类的布局完全匹配。

嗨,我认为问题可能在默认的JsonValueProvider中,但你可以编写一个自定义的:

public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory
    {          

        private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
        {
            IDictionary<string, object> d = value as IDictionary<string, object>;
            if (d != null)
            {
                foreach (KeyValuePair<string, object> entry in d)
                {
                    AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
                }
                return;
            }

            IList l = value as IList;
            if (l != null)
            {
                for (int i = 0; i < l.Count; i++)
                {
                    AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
                }
                return;
            }

            // primitive
            backingStore[prefix] = value;
        }

        private static object GetDeserializedObject(ControllerContext controllerContext)
        {
            if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            {
                // not JSON request
                return null;
            }

            StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
            string bodyText = reader.ReadToEnd();
            if (String.IsNullOrEmpty(bodyText))
            {
                // no JSON data
                return null;
            }

            object jsonData = new JavaScriptSerializer().DeserializeObject(bodyText);
            return jsonData;
        }

        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            object jsonData = GetDeserializedObject(controllerContext);
            if (jsonData == null)
            {
                return null;
            }

            Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            AddToBackingStore(backingStore, String.Empty, jsonData);
            return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
        }

        private static string MakeArrayKey(string prefix, int index)
        {
            return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
        }

        private static string MakePropertyKey(string prefix, string propertyName)
        {
            return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
        }


    }

然后将其添加到Global.asax中的Application_Start中:

    ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());

这个例子使用的是Json.NET

也最好使用ko.mapping插件ko.mapping ,因为你的毕业类可以是可观察的对象:

var jsonModel = ko.mapping.toJSON(graduationClass);

                    $.ajax({
                        url: '/SiteManagement/saveGraduationClass',
                        type: 'POST',
                        dataType: 'json',
                        data: jsonModel,
                        contentType: 'application/json; charset=utf-8',
                        success: function (data) {
                            // get the result and do some magic with it                            
                        }
                    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM