Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass additional data with submit button

I have form, with two buttons:

 <form action="/Book/Crud" method="post">
        <input type="text" name="bookInput" />  
        <button type="submit">Save</button>
        <button type="submit">Save and exit</button>
    </form>

How can I pass to my controller, or, whatever, additional value, which depends on button?
<button type="submit" ?????? >Save</button> What should be here?

I am using Asp.Net Core, with this controller:

public IActionResult Crud(string bookInput)
{
    //removed code for brevity
}
like image 526
Yurii N. Avatar asked Jun 22 '16 16:06

Yurii N.


2 Answers

You can use jquery to solve the issue:

cshtml

<form action="/Book/Crud" method="post">
        <input type="text" name="bookInput" />  
        <button type="submit" name="Submit">Save</button>
        <button type="submit" name="SubmitAndExit">Save and exit</button>
</form> 

jquery

$("form").submit(function () {
     var btn = $(this).find("input[type=submit]:focus" );
     var btnName = btn.attr('name');
     var input = $("<input>")
           .attr("name", "btnName").val(btnName);
     $(this).append(input);
     return true;
});
like image 93
adem caglin Avatar answered Oct 06 '22 02:10

adem caglin


The answer of Bobby Jack is correct. I will elaborate on this answer in order to show how to access this input from within the controller. If you would use the following HTML:

<form action="/Book/Crud" method="post">
    <input type="text" name="bookInput" />  
    <button name="action" value="save" type="submit">Save</button>
    <button name="action" value="save-exit" type="submit">Save and exit</button>
</form>

You could reach the values: 'save' and 'save-exit' by defining another parameter in the controller like this:

// The parameter 'action' is what will contain the values specified in the button.
public IActionResult Crud(string bookInput, string action)
{
    // Implementation
}

The name of the parameter needs to correspond to the value in the 'name' attribute of the form button (in this case 'action'). When the button is clicked, ASP.net will automatically assign the value of the 'value' attribute to the controller parameter. Or more specifically the controller parameter 'action' will have a value of 'save' or 'save-exit' retrieved from the attribute 'value'.

like image 40
Fluous Avatar answered Oct 06 '22 03:10

Fluous