Two or more action buttons in the form of MVC - Best Practice

I have an ASP.NET MVC application with a form. Let's say this form has an arbitrary number of buttons, each of which has its own action.

<input type="button" id="action1" value="One" />
<input type="button" id="action2" value="Two" />
... and so forth

We want the user to click on one and have jQuery fire to submit the form, and then return the form with the new information.

There are several ways to implement this. What is the best practice for creating this elegant design? Please provide code snippets if you can.

+3
source share
2 answers

Set up an object literal of possible actions:

var actions = {
  action1: function(elem) {
    // If you just want to submit the form normally
    $(elem).closest('form').submit();
    ...
  },
  action2: function(elem) {
    // If you wanted to ajax load a url-field into a div
    var url = $('#url_field').val();
    $('.display').load(url);
    ...
  }
}

, ( ) . ('$.live()'), , .

$('input[type=button]').live('click', function(e){
  actions[$(this).attr('id')](this);
});

"actions" (, , , , ).

URL- ajax . "repost [ing] form", , , , .

, .

+2

- ActionMethodSelectorAttribute:

http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx

, AcceptVerbs - , HTTP. , , AJAX/HTTP .., (JSON/XML/etc) ..

- , .. - . , .

, :

  • switch (/action parameter/submit) {} - prodecure, , this.GetType(). GetMethod (submit).Invoke( [] {actiondata}).
  • javascript: input onclick = "$ (this).parents(" form "). attr (" action "," specific url "). submit() - javascript
  • ActionMethodSelectorAttribute - .

, , [SubmitName ( "submit1" )] OnActionExecuting(), ... , .

+3

Source: https://habr.com/ru/post/1720468/


All Articles