2010-12-17 11 views
17

Wiem, że jest wiele postów dotyczących spożywania WCF REST przez JQuery/JSON, ale nie mogę go uruchomić. Obecnie utknąłem w parametrze daty. Poniżej jest moje C# metoda:Wyślij JQuery JSON do WCEST REST przy użyciu daty

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

poniżej jest mój kod 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); 
} 

Mój pierwszy problem jest to, że wciąż otrzymuję błąd data serializacji:

{"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 

mówi to robi Rozpoczęcie/zakończenie tego, jak się zaczyna i kończy.

Moje drugie pytanie brzmi: Czy będę musiał przejechać się modułem wyliczającym lub czy istnieje sposób, aby go wysłać?

Odpowiedz

41

Wyciągnąłem dużo włosów i rzuciłem dużo łez, ale to zadziałało. Zmodyfikowałem formatowanie daty w twojej funkcji naMSJSON. WCF akceptuje ten format, który zrealizowałem dzięki Rick Strahl.

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

Należy również konwertować daty na czas UTC lub dostać wszelkiego rodzaju śmieszne rzeczy, więc:

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

nadzieję, że to pomaga.

+2

Och, to pomogło. Dzięki! –

+0

Anonimowy użytkownik zaproponował dodanie this.getUTCOffset() do kodu prototypu – mplungjan

2

Według: 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.

Twój wyliczający powinno być dobrze.

+0

Zgadzam się ... ale to nie działało ... W efekcie poddałem się i zmieniłem interfejs na ciąg znaków. Dziwne jest to, że wydawało się to poprawne i wszystko w porządku, ale wciąż miałem błąd. – Pascal

0

Oto najczęściej seemless rozwiązanie z This post (zmodyfikowana), które chcesz umieścić na kliencie z JSON.stringify():

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

Który działa w najnowszym IE, Chrome i Firefox dla mnie.

Sprawdź metodę JSON.stringify (metoda natywna) i parametr zastępczy, aby uzyskać wskazówki dotyczące konwersji wyliczenia.

0

Alsalaam Aleykum.

Wszystko, co musisz zrobić, to odpowiedzieć na błąd. Mam na myśli zmianę formatu daty, aby json mógł przetworzyć go na usługę internetową.

Twój kod powinien wyglądać tak:

 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

Nie powinno być ogólna metoda formatować datę poprawnie przed przejściem do WCF.

Metoda mogłaby wyglądać następująco:

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

Jednak teraz, jeśli post byłoby dołączyć wartość offsetu na podstawie rzeczywistej strefy czasowej skąd Piszesz.Aby tego uniknąć, można odpowiednio dostosować przesunięcie.

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

budynku nad odpowiedzią przez @vas powyżej: -

// 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 odbiera datę w odpowiednim formacie. Ważnym dodatkiem jest to, jak przekazaliśmy datę w JSON jako ciąg znaków. Można je uprościć w następujący sposób, łącząc klucz i początek ciągu znaków/Date

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