Kendo UI Grid Update无法将JSON反序列化为IEnumerable< ViewModel>.导致ArgumentException无效的JSON原语 [英] Kendo UI Grid Update unable to deserialize JSON into IEnumerable<ViewModel> results in ArgumentException Invalid JSON primitive

查看:107
本文介绍了Kendo UI Grid Update无法将JSON反序列化为IEnumerable< ViewModel>.导致ArgumentException无效的JSON原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Kendo UI功能网格并尝试实现批处理更新功能.

I am using Kendo UI feature Grid and trying to implement batch Update functionality.

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

Here is what I have done so far:

           $(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)

My View Model (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服务中我的Update Implementation的代码:

Finally, here is the code for my Update Implementation inside the WCF Service:

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

    }

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

When I set a breakpoint inside this function here is what I am seeing for

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

When the line IEnumerable foos = serializer.Deserialize>(Indicators); is executed while debugging I get the following ArgumentException: Invalid JSON primitive: Indicators.System.ArgumentException was unhandled by user code

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,但是在没有将String Indicators作为参数的情况下,我根本无法达到UpdateIndicators方法内部的断点.

Also please note, I tried to modify the WCF Service parameter to use IEnumerable Indicators but was unable to hit the break point inside of my UpdateIndicators method at all without string Indicators as my parameter.

推荐答案

您的JSON已进行URL编码-您应将data设置为已序列化的字符串:

Your JSON is being URL encoded - you should set data to an already serialized string:

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会为您反序列化.

on the server-side; I believe WCF will deserialize that for you.

这篇关于Kendo UI Grid Update无法将JSON反序列化为IEnumerable&lt; ViewModel&gt;.导致ArgumentException无效的JSON原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆