Friday, May 13, 2016

Common Mistake :Asp.net MVC or Web Api and POST Json request

I'm sure most of the folks must be well aware of Post request that is send as Json Raw body request.
I come across very common and trivial mistake that I did when creating my web api request. I was working with my scripting guy and he asked me to form Json request in some format and end up spending an hour to figure out the problem related to my json which was not coming fine.
#Problem: Always check the Variable instead the main class or Model name. Otherwise you will end with JSON request coming in .net web.api as null values.
   
public class SOME_VIEW_MODEL
    {
        public DateTime? DOB { get; set; }
        public IList  childViewModel{ get; set; }
    }

public virtual JsonResult GetMeSomeResults(SOME_VIEW_MODEL someViewModel)
{

}
With respect to above data model design the json can be formed with two request body. #1 Request Body
   {
      "DOB": "",
      "childViewModel": [
        {
          "DOB": "1992-03-21"
        },
        {
          "DOB": "1992-03-21"
        }
      ]
    }
{
    "someViewModel":
    {
      "DOB": "",
      "childViewModel": [
        {
          "DOB": "1992-03-21"
        },
        {
          "DOB": "1992-03-21"
        }
      ]
    }
}
Mind it and double check always that you are using variable in request instead a class name. It is basic concept however we tend to make such mistake. In this case it has to be "someViewModel" instead SOME_VIEW_MODEL

No comments :