Tanwer
Tanwer

Reputation: 1583

Sending n number of parameters in api (aspnet core)

I am trying to call an Web API which is in aspnet core Problem is , the number of parameters are not fixed in this. Parameter can be 2 or 10 ( no of parameters will be between 0 to 15 , a guess ) Below is JS code

$(function () {
            $('#btn').click(function () {
                var src = [
                    {
                        "Question1": "Answer1",
                        "Question2": "Answer2",
                        "Question3": "Answer3",
                        "Question4": "Answer4",
                        "Question5": "Answer5"
                    }
                ];
                $.ajax(
                    {
                        url: 'api/Default/',
                        method: 'POST',
                        dataType: 'JSON',
                        data: JSON.stringify(src),
                        contentType: "application/json",
                        success: function (d) {
                            alert("Success");
                        },
                        error: function (e) {
                            alert("Error please try again");
                        }
                    });
            })
        })

And API

[Produces("application/json")]
[Route("api/Default/")]
public class DefaultController : Controller
{
    [HttpPost]
    public JsonResult apc(string [][] s)
    {
        string str;
        //Code Here
        return Json(true);
    }
}

I also tried adding a list of class as parameter instead of string array

public class param
{
    public string key { get; set; }

    public string Value { get; set; }
}

But Parameter value is always null. I used the same concept in MVC5 and it works perfectly there but not working in .Net Core How can we send multiple parameter here ??

Upvotes: 1

Views: 247

Answers (2)

Nkosi
Nkosi

Reputation: 247018

Because of the dynamic nature of the data to be posted you can use an array of Dictionary

[Produces("application/json")]
[Route("api/Default/")]
public class DefaultController : Controller {
    [HttpPost]
    public JsonResult apc([FromBody]Dictionary<string,string>[] data) {
        var value = data[0]["Question1"]; // Should be "Answer1"
        //Code Here
        return Json(true);
    }
}

Upvotes: 1

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

Try to send the JSON as string and send it like bellow :

 [HttpPost]
public JsonResult apc(string s)
{
    string str;
    //Code Here
    return Json(true);
}

then handle the json from the .NET side

Upvotes: 0

Related Questions