Search code examples
ajaxasp.net-mvcasp.net-ajaxhiddenajax.beginform

How to send each element's ID from Ajax form to action?


I need that, which item I click, to send it's Id to GetProduct() action. I used hidden element, but it does not work:

@using (Ajax.BeginForm("GetProduct", "Product", new AjaxOptions { UpdateTargetId = "getProductResult" }, new { id = "productForm" }))
    {
      foreach (var item in list)
      {
         <a href="#" onclick="$('#productForm').trigger('submit');">@item.Name</a>

        //this hidden always send '1', but I want to send item's Id
        <input type="hidden" id='product_@(item.Id)' name ="id" value="@item.Id"  />
      }

     <noscript>
        <input type="submit" id="sendButton" />
     </noscript>
    }

Where is my wrong? How can I send Id ?


Solution

  • the hidden input have name "id" and it is getting added number of time in for loop. Hence it will not work..

    don't submit the form directly on click of button. store the ID in rel attribute of button. and assign its value to hidden variable when it gets clicked and then submit the form..

    <a href="#"
       rel="@(item.id)"
       onclick="$('#id').val($(this).attr('rel')); ('#productForm').trigger('submit');">
    @item.Name
    </a>
    

    putting the onClick code in separate function would be preffered though :)

    Check this Fiddler