2
votes

I am reading data from Web API and populate a form. When I submit it back to Web API, I get this error:

{"Message":"An error has occurred.","ExceptionMessage":"Property 'StartDate' on type 'MvcApplication1.Models.ProductSale' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)].","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Validation.Validators.ErrorModelValidator.Validate(ModelMetadata metadata, Object container)\r\n at System.Web.Http.Validation.DefaultBodyModelValidator.ShallowValidate(ModelMetadata metadata, ValidationContext validationContext, Object container)\r\n
at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateProperties(ModelMetadata metadata, ValidationContext validationContext)\r\n at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateNodeAndChildren(ModelMetadata metadata, ValidationContext validationContext, Object container)\r\n
at System.Web.Http.ModelBinding.FormatterParameterBinding.<>c_DisplayClass1.b_0(Object model)\r\n at System.Threading.Tasks.TaskHelpersExtensions.<>c_DisplayClass49.b_48()\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"} 1

My date comes Web API as "2013-01-31T16:27:18.503" and posts back as "2013-01-31T05:00:00.000Z". I can intercept the payload before sending to Web API and can use something like http://momentjs.com to parse it, but what should I do? This is driving me nuts!

2
If you're looking for a solution - try applying [DataContract] attribute at the class level as well as [DataMember(IsRequired=true)] on the property. See also these two questions: stackoverflow.com/questions/12234582/…, stackoverflow.com/questions/14079049/…Joanna Derks

2 Answers

1
votes

2013-01-31T16:27:18.503 is an XML Date according to XML spec.

2013-01-31T05:00:00.000Z seems to be ISO 8601 date.

Somewhere this seems to be going wrong. Without knowing about your formatters, what you do on date and how it changes impossible to say.

Date format depends on your formatter. If you use a JSON formatter, this could work differently.

0
votes

The error message has the answer. There is nothing wrong with the data that you are posting. Just put the DataMember(IsRequired=true) attribute on your ProductSales's StartDate property to make validation happy.