Reputation: 1326
I am using Asp.net MVC 5 with Web API 2 and OData. I am using ODataControllers in web api. I have a contact class which have a navigation property company and company have a required attribute on its name property. On web api contact controller's post action i am checking ModelState.IsValid before saving the data. Now Problem is that when i post contact data on web api its ModelState.IsValid property returns false every time because Company Navigation Property have a property Name with Required attribute. so Model state throws error Name field is required. So please help me to exclude company navigation property from validation check. Hoping for some positive responses. Thanks
Upvotes: 0
Views: 1533
Reputation: 59
dudes!
I notices that ten years left ))
Add
ModelState.Remove("Company");
or better
ModelState.Remove(nameof(YourModelName.Company));
to your Controller Post (Create) method, before ModelState.IsValid() check
it's a kind of workaround... "normal" way id to use separate DTO class for addition
Upvotes: 4
Reputation: 1326
No "company":null did not worked. It is also creating company object similar to "company":"" so only solution is posting ajax request without sending "company" in data.
Upvotes: 0
Reputation: 2995
Yes, you are right. company=""
is the root cause of the problem.
I don't know how to work with ajax post method, but can you try changing company=""
to company=null
, then the request body should be like
{
....
"company":null
...
}
I think this request will work. (I don't know whether ajax can do this.)
Upvotes: 1
Reputation: 1326
@FengZhao-MSFT Thanks for your reply but i found the main cause of this problem. This is occuring because when i am posting contact object it also sends company="", companyID=1 in posted data where company is navigation property of contact. so this company="" is creating the problem due to this when data goes to post method it creates a new instance of company and throws model state error for name field required. If we remove company="" from our posted data and only sends companyID problem solves. One more thing we are using a common ajax post method for all our resources so we can't exclude comapny="" from our request. Now we have excluded it on server side using actionfilter where we have removed company validation errors from modelstate. Thanks
Upvotes: 2
Reputation: 76
I'm having the same issue. Actually this type of issue only occurs in OdataController. MvcController action ignores navigation property validations.
Upvotes: 1