0

I have a table, which gets filled at Runtime. In the last Row I want to add one button to each Column and when one button is pressed it shall Link to the same Post method, but with a different value.

<form method="post" asp-action="ChangeAll">
   <input asp-for="DataId" type="hidden" />
 <table>
  <thead>
   .....
  </thead>
  <tbody>
  ....data dynamically loaded
  (
   <td>
       <input type="checkbox" name="boxes" value="@Model.RowId" />
    </td> )

  //last Row:
  <tr>
    <td>
      <input type="submit" value="Update" />
      <input type="hidden" name="selectedAction" value="@MyEnum.Value1" hidden />
    </td>
    ......
   <td>
      <input type="submit" value="Update" />
      <input type="hidden" name="selectedAction" value="@MyEnum.Value20" hidden />
    </td>
  </tr>
 </tbody>
</table>
</form>



[HttpPost]
     public async Task<IActionResult> ChangeAll(int[] boxes, int DataId, string 
    selectedAction){

The problem with the above is that no matter what button I click, it always posts back the value of the first button (MyEnum.Value1). I have tried to add an asp-action="ChangeAll" to each button, but the behaviour stays the same.

So, how can I get the value of the Button I actually clicked?

SuperNev
  • 31
  • 5
  • Does this answer your question? [MVC razor form with multiple different submit buttons?](https://stackoverflow.com/questions/19650345/mvc-razor-form-with-multiple-different-submit-buttons) – Sergey Kudriavtsev Nov 23 '22 at 14:05
  • I mean, it is a Solution, sure. But with that I would have to add twenty ifs/switch to my Code... – SuperNev Nov 24 '22 at 08:31

1 Answers1

1

In your code, All the hidden input have the same name, So when you submit the form. It will bind the first one. You can change your code like this:

<form method="post" asp-action="ChangeAll" id="Form">
 .....
<input type="hidden" name="selectedAction"  id="select" hidden />

    <tr>           
    <td>
      <input type="submit" value="Update" data-action="@MyEnum.Value1" onclick="choice(this,event)"/>         
    </td>
     ........
    <td>
      <input type="submit" value="Update" data-action="@MyEnum.Value20" onclick="choice(this,event)"/>        
    </td>
   </tr>
</form>

<script>
         function choice(a,event){
             event.preventDefault();
             var result = $(a).data("action");
             document.getElementById("select").value = result;
             document.getElementById("Form").submit();
         }
    </script>

In the above code, I only wrote one hidden input and customized an attribute--data-action to accept @MyEnum.Valuexx's value, and then assigned this value to the hidden input.

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12