Update Hidden Field in Repeater Using JQuery

603 views Asked by At

I have a simple grid of stock items that a user can drag from one location to another - subtracting 1 from the source and adding one to the destination.

The initial values are populated using a c# repeater and I'm using JQuery to visualise the drag and drop.

My problem is when I want to click the save button. I iterate through the grid updating a database with the values. Unchanged, the save works (all hidden fields are populated). But when it encounters a recalculated grid item, the hidden field is empty.

Her is my repeater:

<asp:Repeater ID="rptTyres" runat="server">
     <ItemTemplate>
          <li data-id="<%#Eval("TyresId") %>" class="ty"><%#Eval("TyresStockVol") %><asp:HiddenField ID="hfData" runat="server" Value='<%#Eval("TyreStockVol") %>' /></li>
     </ItemTemplate>
</asp:Repeater>

Here is the JQuery that amends the drag and drop values:

if (dragValue > 0) {
    $("[data-id=" + dragAttr + "]").text(dragNew);
    $("[data-id=" + dropAttr + "]").text(dropNew);
    $("input[name$=rptTyres_hfData_" + dragAttr + "]").val(dragNew); //new source total
    $("input[name$=rptTyres_hfData_" + dropAttr + "]").val(dropNew); //new destination total
}

And here is the click event:

protected void btnSave_Click(object sender, EventArgs e)
{
    var tyreId = 1;
    foreach (RepeaterItem item in rptTyres.Items)
    {
        if (item.ItemType == ListItemType.Item
                || item.ItemType == ListItemType.AlternatingItem)
        {
            var hf = (HiddenField)item.FindControl("hfData");
            var hfData = Convert.ToInt32(hf.Value);
            UpdateTyre(tyreId, hfData);
            tyreId ++;
        }
    }
}

I'm pretty sure this bit of code is wrong from a C# point of view;

    $("input[name$=rptTyres_hfData_" + dragAttr + "]").val(dragNew);
    $("input[name$=rptTyres_hfData_" + dropAttr + "]").val(dropNew);

Any suggestions?

EDIT: I've tried using an html hidden field instead and to amend the hidden field value using JQuery:

$("input:hidden[name=hid" + dragAttr + "]").val(dragNew);
$("input:hidden[name=hid" + dragAttr + "]").val(dropNew);

and to read the values to amend the database:

var hfData = Request.Form["hid" + tyreId];

Unfortunately, it picks up values when unchanged, but any hidden field updated by JQuery returns null. I'm banging my head against a brick wall here!!

1

There are 1 answers

0
ComfortablyNumb On

The only way I could get this to work was to place a hardwired block of hidden fields outside of the repeater. No idea why, but at least it's working.