Reputation: 1406
I'm using ASP.NET Web API and I have this POST method in controller:
[Route("Order/{siteId}/{orderId}")]
public HttpResponseMessage Post(long siteId, long orderId, OrderInformation orderInfo)
{
if (ModelState.IsValid) { ... }
}
I have a couple data annotations in OrderInformation class (Required etc.) but unfortunately validation do not work. It is because ModelState do not contains key for orderInfo. It contains only siteId and orderId.
So my question is why orderInfo parameter is not included in ModelState. I have not idea why it works so weird because I use similar code on different places and it works fine.
Edit:
Here is model (OrderInformation class):
public class tOrderInformation
{
[Required]
public string LoyaltyNumber;
[Required]
public string SpecialInstructions;
public bool SendEmail;
...
// few more string properties, no data annotations
}
Edit 2:
I'm sending complex type in body serialized into JSON. I also tried this signature of method:
[Route("Order/{siteId}/{orderId}")]
public HttpResponseMessage Post(long siteId, long orderId, [FromBody] OrderInformation orderInfo)
Upvotes: 0
Views: 1771
Reputation: 1406
Uff I just found what is the problem. There can't be public fields in model, it must be properties.
Upvotes: 4
Reputation: 545
You shouldn't pass complex object in the url. Get the orderinfo from the body of the request
[Route("Order/{siteId}/{orderId}")]
public HttpResponseMessage Post(long siteId, long orderId, [FromBody]OrderInformation orderInfo)
{
if (ModelState.IsValid) { ... }
}
And send the object using json. This way it shouldn't be null.
Upvotes: 1