Search code examples
htmljqueryformsasp.net-corepost

single form and multiple submit (with multiple value)


I Have a "For Loop" In ASP.NET Core Like This :

<button type="submit" Form="FormActive" name="id" value="@item.I"></button>

 <!--It Will Create SomeThing Like This:-->
 <button type="submit" Form="FormActive" name="id" value="1"></button>
 <button type="submit" Form="FormActive" name="id" value="2"></button>
 <button type="submit" Form="FormActive" name="id" value="3"></button>
  ...          ...               ...        ...           4
  ...          ...               ...        ...           99
<!--And This Is My Single Form : -->
    <form id="FormActive" action="/action_page">
</form>

Whats The Problem? why This Form Just Send A httpRequest POST Without"ID" And Value?(infact It Will Send A Post Request With Empty Body)

What I Should To do for send ID

Edit: I cant Remove Form - And I Cant Use +99 Form too maybe i need jquery ... or something?


Solution

  • How about try asp-action , like

    <form id="FormActive" asp-action="Index">
    </form>
    

    Then in controller:

    [HttpPost]
     public IActionResult Index(int id)
     {
        
         return View();
     }
    

    result:

    enter image description here

    Update:

    Try to use <a> tag without With Tag Form

    <a asp-controller="Home" asp-action="Index2" asp-route-id="1"><button>1</button></a>
    

    Then in controller;

     [HttpGet]
     public IActionResult Index2(int id)
      {
       return View();
       }
    

    result:

    enter image description here

    Update2 We can add a hidden <input> in the form to get the id like:

    <button type="submit" Form="FormActive" name="id" value="1">a</button>
    <form id="FormActive"  method="post" asp-controller="Home" asp-action="Index" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed">    
        <input id="buttonid"  type="hidden" name="id" />        
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
        $("button").click(function (e) {      
            var fired_button = $(this).val();
            alert(fired_button);
            $('#buttonid').val(fired_button);
        });
    </script>
    

    result:

    enter image description here