【问题标题】:Kendo UI Grid Update unable to deserialize JSON into IEnumerable<ViewModel> results in ArgumentException Invalid JSON primitiveKendo UI Grid Update 无法将 JSON 反序列化为 IEnumerable<ViewModel> 导致 ArgumentException 无效 JSON 原语
【发布时间】:2013-11-26 21:23:43
【问题描述】:

我正在使用 Kendo UI 功能 Grid 并尝试实现批量更新功能。

这是我到目前为止所做的:

           $(document).ready(function () {
             ("#grid").kendoGrid({
               dataSource:
                   {
                   type: "json",
                   transport:
                        {
                            read: function (options) {
                                $.ajax({
                                    url: "IndicatorService.svc/GetIndicators/" + speedID,
                                    dataType: "json",
                                    success: function (result) {
                                        options.success(result);
                                    }
                                });

                            },

                            update: function(options) {
                                $.ajax({
                                    type: "POST",
                                    url: "IndicatorService.svc/UpdateIndicators",
                                    dataType: "json",
                                    contentType: "application/json",
                                    data: {
                                        Indicators: kendo.stringify(options.data.models)
                                    },
                                    success: function(result) {
                                        // notify the data source that the request succeeded
                                        options.success(result);
                                    },
                                    error: function(result) {
                                        // notify the data source that the request failed
                                        options.error(result);
                                    }
                                });
                            }



                        },
                   batch: true,
                   schema: {
                       type: 'json',
                       model: {
                           id: "IndicatorUID",
                           fields: {
                               IndicatorUID: { type: "guid" },
                               IndicatorName: { type: "string" },
                               LastUpdatedBy: { type: "string" },
                               LastUpdatedDate: { type: "date" },
                               POPL3Commit: { type: "date" },
                               ActualFinish: { type: "date" },
                               PlanOfRecord: { type: "date" },
                               Trend: { type: "date" }

                           }
                       }
                   },
                   pageSize: 10

               },
               height: 430,
               filterable: true,
               sortable: true,
               pageable: true,
               toolbar: ["create", "save", "cancel"],
               editable: true,

               columns: [
                   {
                       field: "IndicatorName",
                       title: "IndicatorName",
                       width: 120
                   },
                   {
                       field: "POPL3Commit",
                       title: "POPL3Commit",
                       format: "{0:MM/dd/yyyy}",
                       width: 120
                   },
                   {
                       field: "PlanOfRecord",
                       title: "PlanOfRecord",
                       format: "{0:MM/dd/yyyy}",
                       width: 120
                   },
                   {
                       field: "Trend",
                       title: "Trend",
                       format: "{0:MM/dd/yyyy}",
                       width: 120
                   },
                   {
                       field: "ActualFinish",
                       title: "ActualFinish",
                       format: "{0:MM/dd/yyyy}",
                       width: 120
                   },
                   {
                       field: "LastUpdatedBy",
                       title: "LastUpdatedBy",
                       width: 120
                   },
                   {
                       field: "LastUpdatedDate",
                       title: "LastUpdatedDate",
                       width: 120
                   }
               ]
           });
       });

我的视图模型(IndicatorGridLineItem)

[DataContractAttribute]
public class IndicatorGridLineItem
{
    #region Private Properties

    /// <summary>
    /// Indicator UID
    /// </summary>
    private Guid _indicatorUID { get; set; }

    /// <summary>
    /// The _indicator name
    /// </summary>
    private string _indicatorName { get; set; }

    /// <summary>
    /// The _commit
    /// </summary>
    private DateTime _pOPL3Commit { get; set; }

    /// <summary>
    /// The _p OR
    /// </summary>
    private DateTime _planOfRecord { get; set; }

    /// <summary>
    /// The _trend
    /// </summary>
    private DateTime _trend { get; set; }

    /// <summary>
    /// The _trend color
    /// </summary>
    private string _trendColor { get; set; }

    /// <summary>
    /// The _actual finish
    /// </summary>
    private DateTime _actualFinish { get; set; }

    /// <summary>
    /// The _last updated by
    /// </summary>
    private string _lastUpdatedBy { get; set; }

    /// <summary>
    /// The _last updated date
    /// </summary>
    private DateTime _lastUpdatedDate { get; set; }

    #endregion Private Properties

    #region Public Properties

    /// <summary>
    /// Indicator UID
    /// </summary>
    [DataMember]
    public string IndicatorUID
    {
        get 
        { 
            return _indicatorUID.ToString(); 
        }
        set 
        {
            Guid newGuid;

            if (Guid.TryParse(value, out newGuid))
                _indicatorUID = newGuid;
            else
                _indicatorUID = Guid.Parse("00000000-0000-0000-0000-000000000000"); 
        }
    }

    /// <summary>
    /// The indicator name
    /// </summary>
    [DataMember]
    public string IndicatorName
    {
        get 
        { 
            return _indicatorName; 
        }
        set 
        { 
            _indicatorName = value; 
        }
    }

    /// <summary>
    /// The commit
    /// </summary>
    [DataMember]
    public string POPL3Commit
    {
        get 
        {
            return DateOutputGenerator(_pOPL3Commit); 
        }
        set 
        {
            _pOPL3Commit = DateInputGenerator(value);
        }
    }

    /// <summary>
    /// The POR
    /// </summary>
    [DataMember]
    public string PlanOfRecord
    {
        get 
        {    
            return DateOutputGenerator(_planOfRecord); 
        }
        set 
        { 
            _planOfRecord = DateInputGenerator(value); 
        }
    }

    /// <summary>
    /// The trend
    /// </summary>
    [DataMember]
    public string Trend
    {
        get 
        {    
            return DateOutputGenerator(_trend); 
        }
        set 
        { 
            _trend = DateInputGenerator(value); 
        }
    }

    /// <summary>
    /// The trend color
    /// </summary>
    [DataMember]
    public string TrendColor
    {
        get 
        {
            return String.IsNullOrEmpty(_trendColor) ? _trendColor : ""; 
        }
        set 
        { 
            _trendColor = value; 
        }
    }

    /// <summary>
    /// The actual finish
    /// </summary>
    [DataMember]
    public string ActualFinish
    {
        get 
        {    
            return DateOutputGenerator(_actualFinish); 
        }
        set 
        { 
            _actualFinish = DateInputGenerator(value); 
        }
    }

    /// <summary>
    /// The last updated by
    /// </summary>
    [DataMember]
    public string LastUpdatedBy
    {
        get 
        { 
            return String.IsNullOrEmpty(_lastUpdatedBy) ? _lastUpdatedBy : ""; 
        }
        set 
        { 
            _lastUpdatedBy = value; 
        }
    }
    /// <summary>
    /// The last updated date
    /// </summary>
    [DataMember]
    public string LastUpdatedDate
    {
        get 
        {    
            return DateOutputGenerator(_lastUpdatedDate); 
        }
        set 
        { 
            _lastUpdatedDate = DateInputGenerator(value); 
        }
    }

    #endregion Public Properties

    /// <summary>
    /// Dates the output generator.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    protected string DateOutputGenerator(DateTime value)
    {
        DateTime beginningOfTime = new DateTime();

        if (beginningOfTime.ToString().Equals(value.ToString()))
            return "";
        else
            return value.ToString();
    }

    /// <summary>
    /// Dates the input generator.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    protected DateTime DateInputGenerator(string value)
    {
        DateTime parsedDate;

        if (DateTime.TryParse(value, out parsedDate))
            return parsedDate;
        else
            return new DateTime();
    }
}

这是 WCF 接口:

[ServiceContract]
public interface IIndicatorService
{
    [OperationContract]
    [WebGet(UriTemplate = "/GetIndicators/{SpeedId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    List<IndicatorGridLineItem> GetIndicators(string SpeedId);

    [OperationContract]
    [WebInvoke(UriTemplate = "/UpdateIndicators", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]  
    void UpdateIndicators(string Indicators);
}

最后,这是我在 WCF 服务中的更新实现的代码:

    public void UpdateIndicators(string Indicators)
    {
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        IEnumerable<IndicatorGridLineItem> foos = serializer.Deserialize<IEnumerable<IndicatorGridLineItem>>(Indicators);

    }

当我在这个函数中设置断点时,这就是我所看到的

string Indicators ="Indicators=%5B%7B%22ActualFinish%22%3Anull%2C%22IndicatorName%22%3A%22Ownership%22%2C%22IndicatorUID%22%3A%220ac1eb81-d44c-4b6a-9c3b-043537805cc7%22%2C%22LastUpdatedBy%22%3Anull%2C%22LastUpdatedDate%22%3Anull%2C%22POPL3Commit%22%3A%222013-11-26T08%3A00%3A00.000Z%22%2C%22PlanOfRecord%22%3Anull%2C%22Trend%22%3Anull%2C%22TrendColor%22%3Anull%7D%5D"

当行 IEnumerable foos = serializer.Deserialize>(Indicators);在调试时执行我得到以下 ArgumentException: JSON 原语无效:Indicators.System.ArgumentException 未被用户代码处理

HResult=-2147024809
Message=Invalid JSON primitive: Indicators.
Source=System.Web.Extensions
StackTrace:
   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)
   at PDD_Web_UI.IndicatorService.UpdateIndicators(String Indicators) in c:\TFS-Newest\PCSO CSE\PDD Web UI\IndicatorService.svc.cs:line 23
   at SyncInvokeUpdateIndicators(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
InnerException: 

另外请注意,我尝试修改 WCF 服务参数以使用 IEnumerable Indicators,但在没有字符串 Indicators 作为参数的情况下根本无法在我的 UpdateIndicators 方法中到达断点。

【问题讨论】:

    标签: c# json wcf kendo-ui kendo-grid


    【解决方案1】:

    您的 JSON 正在被 URL 编码 - 您应该将 data 设置为已序列化的字符串:

    transport: {
        read: {
            url: "IndicatorService.svc/GetIndicators/" + speedID
        },
        update: function (options) {
            $.ajax({
                type: "POST",
                url: "IndicatorService.svc/UpdateIndicators",
                dataType: "json",
                contentType: "application/json",
                data: kendo.stringify({ Indicators: options.data.models }),
                success: function (result) {
                    options.success(result);
                },
                error: function (result) {
                    options.error(result);
                }
            });
        }
    },
    

    另外,你应该可以使用

    void UpdateIndicators(List<Indicator> Indicators);
    

    而不是

    void UpdateIndicators(string Indicators);
    

    在服务器端;我相信 WCF 会为您反序列化。

    【讨论】:

    • 嗨 Lars,感谢您现在的回复我在 kendo.web.min.js 中收到一个错误:localhost:23497/scripts/kendo/kendo.web.min.js 中第 13 行第 26952 列的未处理异常 - 0x800a03ec - Microsoft JScript 运行时错误:预期的 ';'有趣的是,当我在 Visual Studio 中打开并查看该文件时,它似乎有 3 个解析器错误。
    • @user1710400 当您尝试保存时会发生这种情况?我不确定问题出在哪里 - 你可以在你的项目中引用未缩小的 kendo.web.js 以便获得真实的行号(以及其中的代码)吗?查看该代码可能有助于找出问题所在。另外:您使用的是哪个版本?
    • 我不再遇到我之前评论中提到的未处理异常。我必须更新读取的代码,请参阅上面我编辑的 javascript。我在调试时检查的 WCF 服务中仍然得到相同的字符串:“Indicators=%5B%7B%22ActualFinish%22%3Anull%2C%22IndicatorName%22%3A%22testing%22‌​%2C%22IndicatorUID%22 %3A%2200000000-0000-0000-0000-000000000000%22%2C%22LastUpdat‌​edBy%22%3Anull%2C%22LastUpdatedDate%22%3Anull%2C%22POPL3Commit%22%3A%222013-11-27‌​T08%3A00 %3A00.000Z%22%2C%22PlanOfRecord%22%3Anull%2C%22Trend%22%3Anull%2C%22Trend‌​Color%22%3Anull%7D%5D"
    • 嘿拉斯,我在回答这个问题时发布了一个解决方案。感谢您的所有帮助!
    • @user1710400 更新了解决方案...我看到您自己已经想通了。很高兴解决了。
    【解决方案2】:

    好的,我想通了。

    JS代码:

           $(document).ready(function () {
               $("#grid").kendoGrid({
                   dataSource:
                       {
                       type: "json",
                       transport:
                            {
                                read: function (options) {
                                    $.ajax({
                                        url: "IndicatorService.svc/GetIndicators/" + speedID,
                                        dataType: "json",
                                        success: function (result) {
                                            options.success(result);
                                        }
                                    });
    
                                },
    
                                update: function(options) {
                                    $.ajax({
                                        type: "POST",
                                        url: "IndicatorService.svc/UpdateIndicators",
                                        dataType: "json",
                                        contentType: "application/json",
                                        data: JSON.stringify( options.data.models ),
                                        success: function (result) {
                                            // notify the data source that the request succeeded
                                            options.success(result);
                                        },
                                        error: function (result) {
                                            // notify the data source that the request failed
                                            options.error(result);
                                        }
                                    });
                                }
    
    
    
                            },
                       batch: true,
                       schema: {
                           type: 'json',
                           model: {
                               id: "IndicatorUID",
                               fields: {
                                   IndicatorUID: { type: "guid" },
                                   IndicatorName: { type: "string" },
                                   LastUpdatedBy: { type: "string" },
                                   LastUpdatedDate: { type: "date" },
                                   POPL3Commit: { type: "date" },
                                   ActualFinish: { type: "date" },
                                   PlanOfRecord: { type: "date" },
                                   Trend: { type: "date" }
    
                               }
                           }
                       },
                       pageSize: 10
    
                   },
                   height: 430,
                   filterable: true,
                   sortable: true,
                   pageable: true,
                   toolbar: ["create", "save", "cancel"],
                   editable: true,
    
                   columns: [
                       {
                           field: "IndicatorName",
                           title: "IndicatorName",
                           width: 120
                       },
                       {
                           field: "POPL3Commit",
                           title: "POPL3Commit",
                           format: "{0:MM/dd/yyyy}",
                           width: 120
                       },
                       {
                           field: "PlanOfRecord",
                           title: "PlanOfRecord",
                           format: "{0:MM/dd/yyyy}",
                           width: 120
                       },
                       {
                           field: "Trend",
                           title: "Trend",
                           format: "{0:MM/dd/yyyy}",
                           width: 120
                       },
                       {
                           field: "ActualFinish",
                           title: "ActualFinish",
                           format: "{0:MM/dd/yyyy}",
                           width: 120
                       },
                       {
                           field: "LastUpdatedBy",
                           title: "LastUpdatedBy",
                           width: 120
                       },
                       {
                           field: "LastUpdatedDate",
                           title: "LastUpdatedDate",
                           width: 120
                       }
                   ]
               });
           });
    

    WCF 服务:

        public void UpdateIndicators(List<IndicatorGridLineItem> Indicators)
    

    在使用您的答案和此处显示的答案后,我得到了答案: https://stackoverflow.com/a/6323528/1710400

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多