2010-12-17 37 views
17

我知道有很多關於通過JQuery/JSON使用WCF REST的帖子,但是我無法讓它工作。我目前卡在日期參數。下面是我的C#方法:發送JQuery JSON到WCF REST使用日期

[OperationContract] 
[WebInvoke] 
[TransactionFlow(TransactionFlowOption.Allowed)] 
string GoodRegister(DateTime pDtTimeStampTransac, Int32 pIDResource, Decimal pQty, enQtyLogType pQtyGoodLogType); 

下面是我的JavaScript代碼:

/// <reference path="../Scripts/jquery-1.4.1-vsdoc.js" /> 
/// <reference path="json.js" /> 

Date.prototype.toMSJSON = function() { 
    var date = '\\\/Date(' + this.getTime() + ')\\\/'; 
    return date; 
}; 

function botaoclick() { 
    var date = new Date().toMSJSON(); 
    var datavar = { 
    'pDtTimeStampTransac': date, 
    'pIDResource': 1, 
    'pQty': 1 
    }; 
    $.ajax(
    { 
    type: "POST", 
    contentType: "application/json; charset=utf-8", 
    url: "http://desk01:9876/ShopFloorService/script/GoodRegister", 
    dataType: "json", 
    data: JSON.stringify(datavar), 
    //data: '{"pDtTimeStampTransac":date, "pIDResource":"teste", "pQty":"3"}', 
    error: jqueryError, 
    success: function (msg) { 
     alert("back"); 
     var divForResult = document.getElementById("test"); 
     divForResult.innerHTML = "Result: <b>" + msg.d + "</b>"; 
    } 
    } 
) 
} 

function jqueryError(request, status, error) { 
    alert(request.responseText + " " + status + " " + error); 
} 

我的第一個問題是,我不斷收到日期序列化錯誤:

{"ExceptionDetail":{"HelpLink":null,"InnerException":{"HelpLink":null,"InnerException":{"HelpLink":null,"InnerException":null,"Message":"DateTime content '\\\/Date(1292616078638)\\\/' does not start with '\\\/Date(' and end with ')\\\/' as required for JSON.","StackTrace":" at System.Runtime.Serialization.Json.JsonReaderDelegator.ParseJsonDate(String originalDateTimeValue)\u000d\u000a at 

它說,它不開始/結束它的開始和結束的方式。

我的第二個問題是:我是否必須騎上枚舉器,還是有辦法發送它?

回答

41

我拉出很多頭髮,並流下了大量的淚水,但這工作。我將您的中的日期格式修改爲MSJSON函數。 WCF接受這種格式,我通過Rick Strahl感謝。

Date.prototype.toMSJSON = function() { 
    var date = '/Date(' + this.getTime() + ')/'; //CHANGED LINE 
    return date; 
}; 

你還需要將日期轉換爲UTC時間,或者你獲得各種有趣的東西,所以:

var dt = ...; 
    var dt1 = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds())); 
    var wcfDateStr = dt1.toMSJSON(); 

希望這有助於。

+2

哦,它幫助沒事。謝謝! – 2012-06-26 17:55:13

+0

匿名用戶建議將this.getUTCOffset()添加到原型代碼 – mplungjan 2012-07-13 10:08:43

2

據:http://msdn.microsoft.com/en-us/library/bb412170.aspx

DateTime Wire Format

DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc. The actual number ("0500" in this example) and its sign (+ or -) are ignored.

When serializing DateTime, Local and Unspecified times are written with an offset, and Utc is written without.

The ASP.NET AJAX client JavaScript code automatically converts such strings into JavaScript DateTime instances. If there are other strings that have a similar form that are not of type DateTime in .NET, they are converted as well.

The conversion only takes place if the "/" characters are escaped (that is, the JSON looks like "\/Date(700000+0500)\/"), and for this reason WCF's JSON encoder (enabled by the WebHttpBinding) always escapes the "/" character.

你的枚舉應該罰款。

+0

我同意開始......但它沒有工作...我結束了放棄,並改變我的接口的字符串。奇怪的是,它看起來是正確的,一切都好,但我仍然有一個錯誤。 – Pascal 2011-02-03 19:32:17

0

下面是This post(修改))一個主要無縫的解決方案,你把客戶與JSON.stringify(:

jsonData = JSON.stringify([new Date()], 
    function (k, v) { return this[k] instanceof Date ? '/Date(' + v + ')/' : v; }); 

在最新的IE,Chrome和火狐我哪工作。

檢出JSON.stringify(一種本地方法)和用於轉換枚舉的提示的替換參數。

0

Alsalaam Aleykum。

您所要做的就是迴應錯誤。我的意思是更改日期格式,以便json可以將其解析爲Web服務。

你的代碼應該是這樣的:

 function botaoclick() { 
 

 
     var date = new Date(); 
 
     date = "\/Date(" + date.valueOf() + ")\/"; 
 
     // valueOf() method Returns the primitive value of a Date object. 
 

 
     var datavar = { 
 
      'pDtTimeStampTransac': date, 
 
      'pIDResource': 1, 
 
      'pQty': 1 
 
     }; 
 

 
     $.ajax({ 
 
      type: "POST", 
 
      contentType: "application/json; charset=utf-8", 
 
      url: "YOUR URL", 
 
      dataType: "json", 
 
      data: JSON.stringify(datavar), 
 
      error: jqueryError, 
 
      success: function(msg) { 
 
      alert("back"); 
 
      var divForResult = document.getElementById("test"); 
 
      divForResult.innerHTML = "Result: <b>" + msg.d + "</b>"; 
 
      } 
 
     }) 
 
     } 
 

 
     function jqueryError(request, status, error) { 
 
     alert(request.responseText + " " + status + " " + error); 
 
     }

0

應該有傳遞給WCF之前正確格式化日期的通用方法。

的方法看起來是這樣的:

var dateToWcf = function(input) 
{ 
    var d = new Date(input); 
    if (isNaN(d)) return null;  
    var formattedDate = { date : "/Date(" + d.getTime() + ")/" }; 
    return formattedDate; 
} 

但是現在如果您發佈它會追加基於從正在張貼實際的時區偏移值。所以爲了避免這種情況,您可以相應地調整偏移量。

var formattedDate = { date: "/Date(" + d.getTime() + d.getGMTOffset() + ")/" }; 
0

大廈在答覆上述@vas: -

// OrderRecievedDateTime is a proper date string 
var tStart = new Date(OrderRecievedDateTime); 
// Get date in UTC (required for WCF) as morning 
var start = new Date(Date.UTC(tStart.getFullYear(), tStart.getMonth(), tStart.getDate(), 0, 0, 0)); 
// Get the ticks 
var startTicks = start.getTime(); 

// Now build the JSON param (**notice I am passing the date value as a string, by including within quotes. Without this it doesn't takes it**). 
var paramRequest = '{ "request": { "StartDate":"' + '\/Date(' + startTicks + ')\/"' + ' } }'; 

// Hit ajax, no need of any JSON.parse or stringify 
$.ajax({ ..., data = paramRequest ..}); 

WCF接收正確格式的日期。重要的補充是我們如何將JSON中的日期作爲字符串傳遞。可以進一步簡化通過組合鍵如下及/日期字符串

var paramRequest = '{ "request": { "StartDate":"\/Date(' + startTicks + ')\/" } }';