Andrew Simpson
Andrew Simpson

Reputation: 7324

Prevent MVC view submitting

I am trying to integrate a payment api into my MVC 5 asp.net C# app.

The 1st part involves getting a 'token' from that api without submitting my form.

I am relatively new to mvc and I cannot get this to work.

This part of my markup:

@using (Html.BeginForm("NewCard", "Payments", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<form action="" method="POST" id="payment-form">
    <span class="payment-errors"></span>

    <div class="form-row">
        <label>
            <span>Card Number</span>
            <input type="text" size="20" data-stripe="number" value="4242424242424242"/>
        </label>
    </div>

    <div class="form-row">
        <label>
            <span>CVC</span>
            <input type="text" size="4" data-stripe="cvc" value="1223"/>
        </label>
    </div>

    <div class="form-row">
        <label>
            <span>Expiration (MM/YYYY)</span>
            <input type="text" size="2" data-stripe="exp-month" value="10" />
        </label>
        <span> / </span>
        <input type="text" size="4" data-stripe="exp-year"  value="2022"/>
    </div>

    <button type="submit">Submit Payment</button>
</form>
}

$('#payment-form').submit(function (event) {
    var $form = $(this);

    // Disable the submit button to prevent repeated clicks
    $form.find('button').prop('disabled', true);

    Stripe.card.createToken($form, stripeResponseHandler);
    // Prevent the form from submitting with the default action
    event.preventDefault();         //i added this is!
    return false; //from the sample code!
});

the form still submits/posts back.

What am i doing wrong?

Upvotes: 1

Views: 211

Answers (1)

user3559349
user3559349

Reputation:

You have invalid html (nested <form> elements) and the outer form is submitting. Remove the inner

<form action="" method="POST" id="payment-form">

tag and if you want to refer to an id (you could just use $('form').submit(function (event) {) then change the outer form to

@using (Html.BeginForm("NewCard", "Payments", FormMethod.Post, new { id = "payment-form", enctype = "multipart/form-data" }))

Upvotes: 4

Related Questions