Karlman68
Karlman68

Reputation: 118

MVC 5 get value of DropDownList within a table row

I have a view with a table of products that can be added to a shopping cart. Each row has a DropDownList with allowed quantities that can be ordered along with a button to add to cart. Everything is populating and displaying properly. I know how to pass the item ID in the ActionLink but how can I get the value of the DownDownList associated with the table row of the ActionLink that was clicked?

I am guessing possibly using JQuery that fires when the ActionLink is clicked?

I also thought of making every row a form but that seems overkill.

Is there an easy MVC way to do this?

Upvotes: 0

Views: 3780

Answers (2)

Flowra
Flowra

Reputation: 1408

for the table in html:

<div class="table-responsive">
        <table id="employeeTable"class="table table-bordered">
            <thead>
                <tr>
                    <th class="text-center">ُُُEmpId</th>
                    <th class="text-center">Name</th>
                    <th class="text-center">Absense State</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <td>@item.Id</td>
                        <td>@item.Name</td>
                        <td class="text-center">@Html.DropDownList("DDL_AbsentStatus", new SelectList(ViewBag.statusList, "Id", "Name"), new { @class = "form-control text-center" })</td>

                    </tr>
                }
            </tbody>
        </table>
    </div>

in javascript to get the selected value:

//Collect Date For Pass To Controller
    $("#btn_save").click(function (e) {
        e.preventDefault();
        if ($.trim($("#datepicker1").val()) == "") {
            alert("ادخل تاريخ يوم صحيح!")
            return;
        }

        var employeesArr = [];
        employeesArr.length = 0;

        $.each($("#employeeTable tbody tr"), function () {
            employeesArr.push({
                EmpId: $(this).find('td:eq(0)').html(),
                EntryDate: $.trim($("#datepicker1").val()),
                StatusId: $(this).find('#DDL_AbsentStatus').val()
            });
        });

        $.ajax({
            url: '/Home/SaveAbsentState',
            type: "POST",
            dataType: "json",
            data: JSON.stringify(employeesArr),
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                alert(result);
                emptyItems();
            },
            error: function (err) {
                alert(err.statusText);
            }
        });



    })

Upvotes: 0

Karlman68
Karlman68

Reputation: 118

In prepping more info for a proper question and went ahead and solved it. Thank you Stephen for the nudge and info.

I tried putting a Html.BeginForm around each <tr> tag in the details section. This did indeed work for me. I was able to easily get the unique form info to POST for each individual row. However, when I would enable JQuery DataTables the submit would break. DataTables must be capturing the submit or click somehow. Haven't figured that out but it made me try JQuery which seems a much better way to do it.

Here is how I construct the table data row:

@foreach (var item in Model)
{
    <tr>
        <td>
            <img src="@item.GetFrontImage()" width="100" />
        </td>
        <td>
            <strong>@Html.DisplayFor(modelItem => item.DisplayName)</strong>
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CustomerSKU)
        </td>
        <td>
            @Html.DropDownList("OrderQty", item.GetAllowedOrderQuantities(), htmlAttributes: new { @class = "form-control" })
        </td>
        <td>
            <a class="btn btn-default pull-right" data-id="@item.ID">Add to Cart</a>
        </td>
    </tr>
}

This creates a select with id of OrderQty and I embedded the item ID in data-id attribute of the link. I then used this JQuery to capture the info and POST it to my controller. Just have a test div displaying the results in this example:

// Add to Cart click
$('table .btn').click(function () {
    // Gather data for post
    var dataAddToCard = {
        ID: $(this).data('id'),     // Get data-id attribute (Item ID)
        Quantity: $(this).parent().parent().find('select').val()    // Get selected value of dropdown in same row as button that was clicked
    }

    // POST data to controller
    $.ajax({
        url: '@Url.Action("AddToCart","Shopping")',
        type: 'POST',
        data: JSON.stringify(dataAddToCard),
        contentType: 'application/json',
        success: function (data) { $('#Result').html(data.ID + ' ' + data.Quantity); }
    })
});

The JQuery function receives the reference to the link being clicked so I can extract the Item ID from the data-id attribute. I can then get a reference to the dropdown (select) that is in the same row by using .parent.parent (gets me to the <tr> tag) and then just finding the next 'select' tag. Probably pretty obvious to a lot of you.

This works great for my purposes. I can also update other elements with data returned from the POST.

Thank you

Karl

Upvotes: 2

Related Questions