Retrieve Json Data as a IEnumerable

1.3k Views Asked by At

Goal:
Send a json data with many data from frontend to backend.

Problem:
When I send the data to the backend i do not retrieve it as a IEnumerable

What part of the code am I missing?

Info:
*Using JQuery as a frontend
*Using Asp.net mvc as a backend

Thank you!

@{
    ViewData["Title"] = "Home Page";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


<button class="testtest">
    dfdf
</button>

<script type="text/javascript">

    $('.testtest').click(function () {

        var txt = '{"name":"John", "age":30, "city":"New York"}'
        var obj = JSON.parse(txt);

        $.ajax({
            url: '@Url.Action("TestGet")',
            data:
            {
                contactcollection: obj
            },
            dataType: 'json',
            type: 'Get',
            contentType: 'application/json',
            success: function (result) {

                var display = '';


                return;
            }
        });

    });

</script>

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using JsonData.Models;

namespace JsonData.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }


        [HttpGet]
        public JsonResult TestGet(IEnumerable<Contact> contactcollection)
        {

            int ddd = 23;

            return Json(null);
        }
    }

    public class Contact
    {
        public string name;
        public int age;
        public string city;
    }
}
3

There are 3 best solutions below

0
On BEST ANSWER
var values = ['1', '2', '3'];

// Make the ajax call
$.ajax({
    type: "POST",
    url: '@Url.Action("done")',
    data: { ids: values },
    dataType: "json",
    success: function (result) {
        alert('Yay! It worked!');
    },
    error: function (result) {
        alert('Oh no :(');
    }
});

    [HttpPost]
    public JsonResult done(List<string> ids)
    {
        bool data = false;

        if (data)
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
        }
        else
        {
            Response.StatusCode = (int)HttpStatusCode.OK;
            return Json("Message sent!", MediaTypeNames.Text.Plain);
        }
    }

Source

AJAX Post of JavaScript String Array to JsonResult as List<string> Always Returns Null?

https://www.c-sharpcorner.com/article/asp-net-mvc-how-to-use-ajax-with-json-parameters/

Sending a javascript array to code behind(c#) using ajax

Jquery Ajax, return success/error from mvc.net controller

3
On

There is no way to send IEmunerable data via HttpGet. You should try HttpPost method to send data.Then,put your data in request body , and your controller should be:

[HttpPost]
public JsonResult TestGet([FromBody]IList<Contact> contactcollection)
{
    int ddd = 23;

    return Json(null);
}
0
On

I think I see what's going on here. You're telling your controller to expect an IEnumerable<Contact>, but you're actually just passing a Contact. Change your JSON string to

var txt = '{"contactcollection":[{"name":"John", "age":30, "city":"New York"}]}'
var obj = JSON.parse(txt);

and then change your ajax to this:

$.ajax({
        url: '@Url.Action("TestGet")',
        data:obj,
        dataType: 'json',
        type: 'Post',
        contentType: 'application/json',
        success: function (result) {

            var display = '';


            return;
        }
    });

And use POST instead of GET