Passing JS array to controller 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 getSelectedPlace

I get ID

and insert it into an array and fill it action

. My action:

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

      

The firebug placesID

fills up. But in my action places

there is null

. If I change string[]

to simple string

then the result is the same. Where is the problem?

Thank.

+3


source to share


3 answers


My solution:
Add HttpPost

to action and add method="POST"

to form.



+1


source


Pay attention to the traditional serialization of parameters. 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;
}

      

+2


source


I suggest you use only string

. separate it with a comma or whatever else 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 use is onsubmit="getSelectedPlace(this);"

unsafe. useonsubmit="return getSelectedPlace(this);"

+1


source







All Articles