Html button calling an MVC Controller and Action method
To directly call an MVC Controller's Action method with a <form>
, use this:
For asynchronous triggering with AJAX and jQuery:
These snippets are for POST requests and adopt to your specific controllers and actions. Remember to load jQuery for AJAX.
Click and go: No-form button redirection
Do away with forms entirely when you just need redirection. Use an input button with type="button"
and the onclick
attribute:
With Razor syntax, this creates a non-POST button that redirects the user to the right URL.
Modern times: AJAX calls without page refresh
Stay on the page while making action calls via AJAX:
This initiates independent HTTP requests without causing page refresh, keeping users as hooked as to refreshing Reddit feeds.
Hidden mines: Common pitfalls and solutions
Beware of the sneaky errors:
- Unintentionally submitting a form? Happens when a button inside a
<form>
lackstype="button"
. $
not working? Check if jQuery got an invite.Url.Action
not resolving correctly? Probably forgot to@
it.
Helpers to the rescue: MVC View HtmlHelpers
Use MVC's Html Helpers to keep your markup clean:
It generates an a
tag that is styled and behaves like a button. Let's say, it's a secret identity kind of thing!
Non-form input buttons: Best practices
Here are some solid best practices for your type="button"
heroics:
- Indicate
type="button"
explicitly and avoid untimely page refreshes. - Using
@Url.Action()
in Razor views ensures correct routing. - AJAXify for a more seamless user experience.
- Always load the jQuery combat gear if you're going AJAX.
- Remember that MVC requests have a lifecycle, like that gym routine you never started.
- The different button methods do affect SEO and UX. Tread wisely.
With these in mind, your button battles won't leave you hitting the panic button!
Was this article helpful?