简体   繁体   中英

Empty Json Array is received on Post

i have an MVC application that is calling a web api to pass some data.

MVC-code

     [AcceptVerbs(HttpVerbs.Post)]
    public async System.Threading.Tasks.Task<ActionResult> StudentViewModels_Create([DataSourceRequest]DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<StudentViewModel> studentviewmodels)
    {
        using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
        {
            string  baseUrl = "http://localhost:51514/api/Students";
            client.BaseAddress = new Uri(baseUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            JArray postData = new JArray();
            //postData.Add(JsonConvert.SerializeObject(request));
            foreach(StudentViewModel student in studentviewmodels)
            {
                postData.Add(JsonConvert.SerializeObject(student));
            }
           // call the web-api and pass the data
           System.Net.Http.HttpResponseMessage response = await client.PostAsync(baseUrl, new StringContent(new JavaScriptSerializer().Serialize(postData), Encoding.UTF8, "application/json"));
            if (!response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsStringAsync();
            }
        }

        // this will return new data
        //return Json("");
    }

here is picture of the data that is in postData variable before it is sent

在此处输入图片说明

However, when the call reaches the Api, the Json array is empty.

Web-api

    public  IHttpActionResult Students_Create(JArray inputData)
    {

        var students = new List<Student>();

        for (int i = 1; i<inputData.Count; i++)
        {
            var tempStudent = new Student();
            tempStudent = (Student)JsonConvert.DeserializeObject(inputData[i].ToString());
            students.Add(tempStudent);
        }

        // Will keep the inserted entitites here. Used to return the result later.
        var entities = students;
        if (ModelState.IsValid)
        {
            using (var northwind = new StudentEntities())
            {
                foreach (var student in students)
                {
                    // Create a new Student entity and set its properties from the posted StudentViewModel.
                    var entity = new Student
                    {
                        Studentid = student.Studentid,
                        Firstname = student.Firstname,
                        Lastname = student.Lastname,
                        Age = student.Age
                    };
                    // Add the entity.
                    northwind.Students.Add(entity);
                    // Store the entity for later use.
                    entities.Add(entity);
                }
                // Insert the entities in the database.
                northwind.SaveChanges();
            }
        }

        return Json(db.Students);
    }

picture of inputData variable

在此处输入图片说明

Any ideas as to why this is happening?. thanks for the help.

Not an answer, but more of an observation of the code you provided. You don't appear to be calling your Students_Create method anywhere in the StudentViewModels_Create . Which leads me to believe you are passing the returned result of StudentViewModels_Create to Students_Create which will not work since StudentViewModels_Create returns an empty Json object ( return Json("") ).

The problem is with the Json Array. this piece of code in the MVC-code section

        JArray postData = new JArray();
        //postData.Add(JsonConvert.SerializeObject(request));
        foreach(StudentViewModel student in studentviewmodels)
        {
            postData.Add(JsonConvert.SerializeObject(student));
        }

when i pass the array through the serializer

       var serializer = new JavaScriptSerializer();
       var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(postData);
       var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

       // pass the data to the api
       System.Net.Http.HttpResponseMessage response = await client.PostAsync(baseUrl, stringContent);

the json varaible only contains an empty array, so what is passed to the api, is an empty array. hence why i was only getting an empty array.

I decided to try an ArrayList instead of a JArray, then passed it through the serializer and it worked. I am not 100% certain as to why this solved the issue, i am still researching for a concrete reason.

        ArrayList postData = new ArrayList();
        postData.Add(JsonConvert.SerializeObject(request));
        foreach (StudentViewModel student in studentviewmodels)
        {
            postData.Add(JsonConvert.SerializeObject(student));
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM