0

I have the following HTML:

using (Html.BeginForm("EmailSend", "Home", FormMethod.Post))
{
code to enter email and press submit
}

and a void controller:

[HttpPost]
[ValidateAntiForgeryToken]
public void EmailSend()
{
code to send email
}

Obviously since I'm dealing with a void controller it has no view to show. I just want to trigger this controller from my submit button in my view, without asking for a redirect. I thought, that since this isn't an ActionResult it should understand?

How do trigger my controller without redirecting? Would i have to use jQuery or Ajax?

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
Jeppe Christensen
  • 1,680
  • 2
  • 21
  • 50

1 Answers1

0

Posting from the browser expects something to show back to the user. You could return, for instance:

return Content("OK");

But then the use is going to literally see plain text "OK" response. If you want to trigger a fire-and-forget operation, either open a new window to this post operation (can add _target="blank" to the form) and then return a dummy view with a confirmation, or JS to close the window, or whatever.

OR, send an AJAX request is really easy with jQuery.

$.ajax({ 
   type: "post",
   url: "@Url.Action("EmailSend")",
   data: $("#form").serialize(),
   success: function() { alert("Email successful"); },
   error: function() { alert("An error occurred"); }
});

Or something like that, where $("#form") refers to an HTML form, and the parameters get serialized and sent up to the server. MVC will still do the object property to form parameter matching it does with standard HTTP POST operations.

Here's another example. There are other plugins that are options too.

Community
  • 1
  • 1
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • Thank you for your answer! - Would i then have to forget about my beginform? remember, i have an input form from which i would very much like to pass a parameter to the controller when i press submit. – Jeppe Christensen Feb 17 '17 at 20:10
  • Form will work fine; that is what $("#form").serialize() is; it takes the form (give it an ID and replace #form with #THATID) and serializes it into name/value parameters to pass along, so whether an AJAX post or standard HTTP post, both will work the same way. – Brian Mains Feb 19 '17 at 03:07