You can choose the URL in which the form should be published (and therefore the action invoked) in different ways, depending on browser support:
- for new browsers that support HTML5, you can use the submit button formaction attribute
- for older browsers that do not support this, you need to use JavaScript, which changes the action attribute when the button is pressed and before sending
This way you do not need to do anything on the server side.
Of course, you can use the Url extension methods in your Razor to indicate the action of the form.
For browsers that support HMTL5: simply specify the submit buttons as follows:
<input type='submit' value='...' formaction='@Url.Action(...)' />
For older browsers, I recommend using an unobtrusive script like this (include it in your βlayoutβ):
$(document).on('click', '[type="submit"][data-form-action]', function (event) { var $this = $(this); var formAction = $this.attr('data-form-action'); $this.closest('form').attr('action', formAction); });
NOTE. This script will handle a click for any element on the page with type=submit and data-form-action attributes. When this happens, it takes the value of the data-form-action attribute and sets the action of the contained form to the value of this attribute. Since this is a delegated event, it will work even for HTML loaded using AJAX, without additional steps.
Then you just need to add the data-form-action attribute with the desired data-form-action url to your button, for example:
<input type='submit' data-form-action='@Url.Action(...)' value='...'/>
Please note that clicking the button changes the action of the form, and immediately after that the browser sends the form to the desired action.
As you can see, this does not require special routing, you can use the standard Url extension methods, and you have nothing special in modern browsers.
JotaBe Jan 14 '14 at 16:08 2014-01-14 16:08
source share