MVC In Html.Begin form need two buttons call diffe

2019-07-24 18:56发布

问题:

Frnds i want to submit data to two different controllers using two different buttons on one form and i want that both buttons call different actions and also provide all the values of the form to their respected controller.

回答1:

You can do this with JavaScript like so:

HTML

<form method="POST" action="/">
    ... The Rest Of Your Form ...
    <input type="Submit" id="btn-1" name="btn-1" />
    <input type="Submit" id="btn-2" name="btn-2" />
</form>

JavaScript

(function(d) {
    var form = d.getElementsByTagName('form')[0],
        targetBtn;
    form.onsubmit = function(e) {
        e.preventDefault();
        targetBtn = e.explicitOriginalTarget.id;

        //Set the form action based on the id of the button that submitted it
        if(targetBtn === 'btn-1') {
            form.action = '/foo';
        } else {
            form.action = '/bar'
        }

        //Submit your form
        form.submit();
    };
}(document));

All you need to do is make sure this code is placed after the from in the HTML markup or add it to a jQuery document.ready function.



回答2:

here is a good article that can help you accomplish what you want

http://blog.ashmind.com/2010/03/15/multiple-submit-buttons-with-asp-net-mvc-final-solution/