user348173
user348173

Reputation: 9278

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.

Upvotes: 3

Views: 2966

Answers (3)

user338195
user338195

Reputation:

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;
}

Upvotes: 2

user348173
user348173

Reputation: 9278

My solution:
Add HttpPost to action and add method="POST" to the form.

Upvotes: 1

tusar
tusar

Reputation: 3424

I would suggest you to use string only. separate it by comma or any other notation you want.

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

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

In action,

public ActionResult Buy(string places)
        {
            string[] placesArray = places.Split(",");
            return new EmptyResult();
        }

Also using onsubmit="getSelectedPlace(this);" is not safe. use onsubmit="return getSelectedPlace(this);"

Upvotes: 1

Related Questions