Search code examples
c#asp.net.netasp.net-ajax

Pass a lot of parameters (ajax, asp.net)


I want to pass some parameters via ajax function. I was able to pass the string list or 2 parameters (int type). I'm having trouble passing a list and an int parameter. Ultimately, there may be even more parameters than two.

My example:

.cs file:

public string AddListElement(int secId, List<string> fieldsList)
{
//code...
return "a";
}

.cshtml file:

<script>
    function AddElement(idSection) { 
        var stringArray = new Array();
        stringArray[0] = "item1";
        stringArray[1] = "item2";
        stringArray[2] = "item3";
        $.ajax({
            type: "POST",
            url: "/BK/User/AddListElement",
            data: {
                secId: idSection,
                fieldsList: stringArray,
            },
            dataType: "json",
            traditional: true,
        }).fail(function () {
            //code...
        }).done(function (data) {
            //code...
        });
    }
</script>

//other code...

<div class="form-group main-center2 col-8 mt-2">
    <a class="btn btn-success btn btn-block" onclick="AddElement(@Model.Section[i].Id);" href="#">
        Dodaj
    </a>
</div>

In this case, idSec is well passed but the list is null. I was able to pass it well by passing the idSec in the Url and the list like this. But in my opinion it's not the best solution, especially if I want more parameters, e.g. 2 lists and 3 int parameters.

How can I pass multiple parameters like this? Assuming that the parameters are different: int, string, list. I read similar topics but no way worked for me.

PS.


Solution

  • The best way to receive JSON content from body is define a model according to the attributes of JSON, like your situation, you can define this:

    public class ReceiveData
    {
        public int secId { get; set; }
        public List <string > fieldsList { get; set; }
    }
    

    And the controller:

    public string AddListElement(ReceiveData data)
    {
    //code...
    return "a";
    }
    

    But if you do not want to define a extra model, you can use a Dictionary<string, object> to hold all the data you want to receive from POST:

    public string AddListElement(Dictionary<string, object> keyValuePairs)
    {
        //code...
        return "a";
    }
    

    Only one parameter per action may be bound from body