Search code examples
c#asp.net-corerazor-pages

Get the value for multiple button with one form in one method


I am using new .NET Core Razor Pages. If I have multiple button, how do I get the value of each button?

Example in my razor pages, I have 2 buttons:

<form method="post">
        <button type="submit" value="2020" id="btn1">2020</button>
        <button type="submit" value="2019" id="btn2">2019</button>
</form>

and in my code behind:

public void OnPost()
{
 // How to get btn1 value (2020) and btn2 value (2019) here?
}

Solution

  • As John said,you can only retrieve the value of the button that was used to submit the form. If you want to post both of the buttons,put them into hidden variables is a good approach.

    Notes: asp.net core model binding system will bind the value by the name in html element not id.

    One way is manually add these inputs:

    <form method="post">
        <input hidden  value="2020" name="btn1"/>
        <input hidden  value="2019" name="btn2"/>
        <button type="submit" value="2020" id="btn1">2020</button>
        <button type="submit" value="2019" id="btn2">2019</button>
    </form>
    

    Another way is using jquery to automatically add inputs:

    <form method="post">
        <button type="submit" value="2020" id="btn1">2020</button>
        <button type="submit" value="2019" id="btn2">2019</button>
    </form>
    
    @section Scripts
    {
    <script>
        $("form").submit(function () {
            $("button[type=submit]").each(function (i) {
                i++;
                var value = $(this).val();
                var input = $("<input>")
                    .attr("type", "hidden")
                    .attr("name", "btn" + i).val(value);
                $('form').append(input);
    
            });
            
        });
    </script>
    }
    

    Backend:

    public void OnPost(int btn1,int btn2)
    {
       //do your stuff...
    }
    

    Result: enter image description here