Search code examples
c#asp.net-mvcactionlink

ActionLink to pass a input value from a different table cell to controller method


I'm working in MVC. I have a table with a bunch of rows. One cell contains an 'Order' button, and a different cell contains a numeric input where the user can specify the quantity of the item he wants to buy? How do I pass through the quantity value in my ActionLink from the input cell? The issue here is not in finding a text value, but rather finding the text value of a specific row

enter image description here

Table Cells

        <td><input id="itemQuantity" type="number" value="1" min="1" max="@item.QuantityInStock" size="10" class="universalWidth"/></td>
        <td>@Html.ActionLink("Order", "OrderTuckShop", new { id = item.IngredientId, quanity = ???}, new { @class = "btn btn-success universalWidth" })</td>

Method Call

public ActionResult OrderTuckShop(Guid? id, int quantity)

Solution

  • You cannot add the value of the textbox in your ActionLink() method because its razor code, and that is parsed on the server before its sent to the client. In order to respond to client side events you need to use javascript/jquery.

    Create a manual link and add the IngredientId as a data- attribute and add an additional class name to use as a selector

    <td>
        <a href="#" data-id="@item.IngredientId" class="order btn btn-success universalWidth">Order</a>
    </td>
    

    In addition, remove the id="itemQuantity" in the input (duplicate id attributes are invalid html) and add a class name as a selector

    <input class="quantity" type="number" ... />
    

    Then include the following script to read the value of the input and make a redirect

    var baseUrl = '@Url.Action("OrderTuckShop")';
    $('.order).click(function() {
        var id = $(this).data('id');
        var quantity = $(this).closest('tr').find('.quantity').val();
        location.href = baseUrl + '?id=' + id + '&quanity=' + quanity;
    });
    

    However, the name of the method suggests you perhaps should be making a POST, not a GET?