3

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.

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);"

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.