Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing JS array to controller's action

I have the following code:

 <form action="" onsubmit="getSelectedPlace(this);" target="_blank">
        <div class="wrap_input">
            <input type="submit" id="myDiv" class="btn buy_btn" value="Done">
        </div>
        </form>

 function getSelectedPlace(form) {
        var placesID = new Array();
        $(".place.green").each(function () {
            placesID.push($(this).attr("id"));
        });

        form.action = "/Pay/Buy?places=" + placesID;
        return true;
    }

In the getSelectedPlace I get ID and push it in the array, and fill action. My action:

 public ActionResult Buy(string[] places)
            {
                return new EmptyResult();
            }

In the firebug placesID is filled. But in my action places is null. If I change string[] to simple string then result is the same. Where is a problem?

Thanks.

like image 631
user348173 Avatar asked May 20 '26 11:05

user348173


1 Answers

Please notice traditional parameter serialization. More details here: http://api.jquery.com/jQuery.param/

<script type="text/javascript">

    var strArray = new Array();

    strArray[0] = "P1";
    strArray[1] = "P2";

    var params = { data: strArray };

    $.ajax({
        type: "GET",
        url: "/Home/Test",
        data: params,
        dataType: "json",
        traditional: true
    });
</script>
}

Controller:

public ActionResult Test(string[] data)
{
    @ViewBag.Test = data[0]; // Data will be set to P1
    return null;
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!