views:

89

answers:

2

How is it possible to enable the following JavaScript function, sending a POST request, to recieve productID parameter not as a single string variable but as a collection of productID's?

i.e. to get in output a string like:

"productId=126504&productId=126505&productId=126506&productId=126507&productId=126508"

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
 <script type="text/javascript">
 function addToCart(productId, returnUrl) {
    var form = $(document.createElement('form'))
    .attr('action', '/products/addtocart')
    .attr('method', 'post')
    .append(
        $(document.createElement('input'))
            .attr('type', 'hidden')
            .attr('name', 'productId')
            .val(productId)
    )
    .append(
        $(document.createElement('input'))
            .attr('type', 'hidden')
            .attr('name', 'returnUrl')
            .val(returnUrl)
    );
    $('body').append(form);
    form.submit();
}
</script>

Edit:

Just to be more clear: When calling this function with a parameter 126504 the function outputs productId=126504. How to pass multiple productID's 126504,126505,126506,126507,126508 in order to get the function output 126504&productId=126505&productId=126506&productId=126507&productId=126508 ?

I call the function from a Silverlight app:

 HtmlPage.Window.Invoke("addToCart", "126504", "http://localhost:10930/Products");
+3  A: 

Add multiple input items with the same name on the same form, and you should get exactly what you're looking for.

Stan Rogers
In fact, that's what I was looking for - how to implement it using JavaScript
rem
A: 

Sorry if my question was a little unclear. Here it is a variant of the function, I've managed to start working as I wanted:

    function addToCart3(path, params, method) {
    method = method || "post"; 
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for (var i = 0, l = params.length; i < l; i++ ) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", "productId");
        hiddenField.setAttribute("value", params[i]);
        form.appendChild(hiddenField);
    }
    document.body.appendChild(form); 
    form.submit();
}

If passing to this function an array of string, the server gets the data as required

string[] arrstrpostdata = new string[] { "126504", "126505", "126506", "126507", "126508", "126509" };
HtmlPage.Window.Invoke("addToCart3", "http://localhost:10930/Cart/AddCollToCart", arrstrpostdata);
rem