2013-09-25 2 views
0

ajax로 객체를 asp.net 서버로 보내고 싶습니다. 객체에 더 이상 인식되지 않는 datetime 속성이 있습니다. 매개 변수의 datetime이 기본값 => 0001.01.01자바 스크립트 날짜를 asp.net 서버로 보냅니다.

var a = {start: new Date(), title: "asdf", description: "asdfasdf", allDay: true, end: new Date()}; 

$.ajax({ 
      url : m_serverName + "/api/calendar", 
      type : "post", 
      data : a, 
      dataType: 'json', 
      success : function() { 
       console.log("ok") 
      }, 
      error : function(request, status, error) { 
       console.log(request) 
      }, 
      xhrFields : { 
       withCredentials : true 
      } 
     }); 

이 방법은 단지 한 가지 방법 일뿐입니다. 내가 toJSON을 사용하면 JS로 서버에 보냅니다.

서버 코드 : 나는 somany 객체와 배열이있는 경우가 매우 어렵 기 때문에

public HttpResponseMessage Post(CalendarEvent calendarEvent) 
     { 
      int id = -1; 

      var httpCookie = HttpContext.Current.Request.Cookies["token"]; 
      if (httpCookie != null) 
       if (!int.TryParse(httpCookie.Value, out id)) 
        return Request.CreateResponse(HttpStatusCode.OK, false); 
       else 
       { 
        int employeeId = service.GetByEmployeeDevice(id).Id; 
        return Request.CreateResponse(HttpStatusCode.OK, 
                service.GetEventsById(employeeId)); 
       } 

      return Request.CreateResponse(HttpStatusCode.OK, false); 
     } 

도메인 모델

[JsonObject] 
    public class CalendarEvent 
    { 
     [JsonProperty("id")] 
     public int Id { get; set; } 

     [JsonProperty("employeeId")] 
     public int EmployeeId { get; set; } 

     [JsonProperty("title")] 
     public string Title { get; set; } 

     [JsonProperty("description")] 
     public string Description { get; set; } 

     [JsonProperty("location")] 
     public string Location { get; set; } 

     [JsonProperty("partner")] 
     public string Partner { get; set; } 

     [JsonProperty(PropertyName = "allDay")] 
     public bool AllDay { get; set; } 

     [JsonProperty(PropertyName = "start")] 
     public DateTime Start { get; set; } 

     [JsonProperty(PropertyName = "end")] 
     public DateTime End { get; set; } 

     [JsonProperty(PropertyName = "type")] 
     public int Type { get; set; } 

     [JsonIgnore] 
     public Employee Employee { get; set; } 

     //navigation property 
     //public ICollection<AgentDevice> Devices { get; set; } 
    } 

어떻게, 어떤 convertation없이, 아약스에 의해이를 보낼 수 있습니다.

답변

1

당신은 ISO 8601 문자열로 보낼 수 있습니다 :

var a = { 
    start: (new Date()).toISOString(), 
    title: "asdf", 
    description: "asdfasdf", 
    allDay: true, 
    end: (new Date()).toISOString() 
}; 

서버에 타격되는 ASP.NET 웹 API가 제대로 날짜 시간 인스턴스로 직렬화 할 수 Newtonsoft JSON 시리얼 라이저를 사용합니다.

+0

나는 toJSON 메서드를 사용할 수 있으며, 서버는 그것을 인식 할 것이다. 그러나 나는 더 많은 수천 개의 아이템을 가진 배열을 가지고있다. 모든 배열 항목의 모든 날짜 속성을 변환해야합니까? – user1693057

+1

예,해야합니다. –

+0

누오, whyyy? 나는 그것을 믿기를 원하지 않는다. – user1693057

0

입력 된 목록/배열 ... List<CalendarEvent> 또는 CalendarEvent[]을 데이터 형식으로 사용하면 ISO-8601 인코딩 날짜를 적절하게 디코딩해야합니다.

+0

나는 이해한다. 그러나 날짜 객체를 JSON 또는 ISOString으로 변환해야하기 전에 그렇지 않습니까? – user1693057

+0

JavaScript에서 JSON.stringify (...)를 사용하여 일련 번호를 지정할 때 기본값은 ISO-8601 스타일 datetime으로 UTC/GMT를 사용하여 날짜/시간 인스턴스를 직렬화하는 것입니다. – Tracker1

0

비밀은 다음과 같습니다. JsonConvert.DeserializeObject (customerJSON);

public HttpResponseMessage Post([FromBody]String customerJSON) 
     { 
      if (customerJSON != null) 
      { 
       int id = -1; 

       var httpCookie = HttpContext.Current.Request.Cookies["token"]; 

       Customer customer = JsonConvert.DeserializeObject<Customer>(customerJSON); 


       if (httpCookie != null) 
        if (!int.TryParse(httpCookie.Value, out id)) 
         return Request.CreateResponse(HttpStatusCode.OK, false); 
        else 
        { 
         customer.ContactId = employeeService.GetByEmployeeDevice(id).Id; 
         return Request.CreateResponse(HttpStatusCode.OK, 
                 service.Add(customer)); 
        } 
      } 

      return Request.CreateResponse(HttpStatusCode.OK, false); 
     } 
관련 문제