0

As the title for my question states, i wish to post a registration form to my controller via ajax instead of a submit button within a BeginForm.

HTML looks like this:

@Html.LabelFor(m => m.Email)<br />
@Html.TextBoxFor(m => m.Email)<br />
@Html.LabelFor(m => m.Password)<br />
@Html.TextBoxFor(m => m.Password)<br />
@Html.LabelFor(m => m.Name)<br />
@Html.TextBoxFor(m => m.Name)<br />
<p>
    <button type="submit" id="sbmt">Register</button>
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
</p>

My controller method looks like this:

public ActionResult Registration(Users model)
{
//code for registration of user
}

i want my ajax to pass just the model to my controller. In other words, i dont want to declare multiple string arguments in my controller.

My ajax so far looks something like this:

$("#sbmt").click(function (e) {

    e.preventDefault();

        $.ajax({
            type: 'POST',
            url: "@Url.Action("Register", "Auth")",
            data: { WHAT SHOULD I PASS HERE? },
        }).done(function (res) {
            if (res.status === "success") {
                $("#MailFoot").hide();
                $("#ty").text("Thank you!");
            }
            else {
                alert("Error sending email");
            }
    });
});

I have no idea how i should wrap my data and pass it to my controller. Any help is therefore appreciated.

Jeppe Christensen
  • 1,680
  • 2
  • 21
  • 50
  • Its just `data: $('form').serialize(),` (and don't use `Ajax.BeginForm()` - the `$.ajax()` methods gve you far more flexibility –  Mar 07 '17 at 23:49
  • Thank you for your answer! Can you give me an example of how that would look? would it require me to wrap it inside a form element? – Jeppe Christensen Mar 07 '17 at 23:53
  • Your form controls just need to be inside `
    ` tags (which they should be anyway). And you do not handle the `.click()` event - you should be handling the forms `.submit()` event
    –  Mar 08 '17 at 00:01
  • so what you say, is that my selector should be `$('form').submit(function()` too? – Jeppe Christensen Mar 08 '17 at 00:04
  • Yes, and if you want client side validation, you should be testing `if($(this).valid())` and cancel the submit if its not. –  Mar 08 '17 at 00:06
  • Thats great! thank you :-) – Jeppe Christensen Mar 08 '17 at 00:56

1 Answers1

-2

You should use AjaxExtensions.BeginForm you can check how to use it here. If you want an example you can view the answer for this question.

Community
  • 1
  • 1
Ezequiel
  • 125
  • 7