object的预期格式DateTime
不是 jQuery 日期选择器返回的格式。WCF 需要 ASP.NET 格式的日期(例如,\/Date(1234567890)\/
)。
不过,您可以使用其他格式,但这并不简单(至少在 .NET 4.0 之前不会;在 4.5 上这会好很多)。基本上,您将使用一个字符串属性(如果您的服务在完全信任下运行,它可以是私有的),该属性将从线路中获取值,然后DateTime
在序列化过程中将其连接到一个属性。在http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx上有关于这个技巧的更多信息,你可以在下面的代码中看到它。
namespace StackOverflow_11105856
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
string UpdateEmployee(Employee Employee);
}
public class Service : IService1
{
public string UpdateEmployee(Employee Employee)
{
return string.Format("Name={0},Hired={1}", Employee.Name, Employee.Hired.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
[DataContract]
public class Employee
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Department { get; set; }
[DataMember]
public int Salary { get; set; }
public DateTime Hired { get; set; }
[DataMember(Name = "Hired")]
private string HiredForSerialization { get; set; }
[OnSerializing]
void OnSerializing(StreamingContext ctx)
{
this.HiredForSerialization = this.Hired.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
[OnDeserializing]
void OnDeserializing(StreamingContext ctx)
{
this.HiredForSerialization = "1900-01-01";
}
[OnDeserialized]
void OnDeserialized(StreamingContext ctx)
{
this.Hired = DateTime.ParseExact(this.HiredForSerialization, "MM/dd/yyyy", CultureInfo.InvariantCulture);
}
}
}
和 jQuery 调用:
function StackOverflow_11105856_Test() {
var url = "/StackOverflow_11105856.svc/UpdateEmployee";
var data = {
Name: "John Doe",
Department: "Accounting",
Salary: 50000,
Hired: $("#StackOverflow_11105856_datepicker").val()
};
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
data: JSON.stringify({ Employee: data }),
success: function (result) {
$("#result").text(result.UpdateEmployeeResult);
}
});
}