문제

I am making an account activation method. Everything looks fine. But I think that I am missing something.. my activation method works twice times. I am new in web.

this is my method

[HttpPost]
public ActionResult Active(string code)
{            
     return Content("Your account Successfully Activated");
}

and here is html&jquery code

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        Yout Aktivasyon Code:
        <div class="editor-field">
            <input type="text" id="ActivationCode"/>            
        </div>

        <input type="submit" value="Active"/>
    </fieldset>
}

<script type="text/javascript">

    $(function () {

        $('form').submit(function () {

            $.ajax({
                url: "@Url.Action( "Active", "Account")",
                type: "post",
                data: { code: $('#ActivationCode').val() },
                success: function (result) {
                    console.log("successful\n" + result);
                },

                error: function (request, status, error) {
                    console.log("error");
                }
            });
        });
    });
</script>

I put a put a breakpoint in Active method and check "code" parameter. When I submit my form, Active method triggers and code has value that what is in textbox. and I push F5 to continue, after that Active method triggers again and code value is null

I cant find out my mistake why it works twice?

도움이 되었습니까?

해결책

It can be that you are doing an ajax request and a normal post after, because you are not preventing the default behavior. Try preventing the default behavior:

$(function () {

    $('form').submit(function (e) { // Add the event parameter -> e

        // Prevent the default behavior.
        e.preventDefault();

        $.ajax({
            url: "@Url.Action( "Active", "Account")",
            type: "post",
            data: { code: $('#ActivationCode').val() },
            success: function (result) {
                console.log("successful\n" + result);
            },

            error: function (request, status, error) {
                console.log("error");
            }
        });

        // Also return false for the default behavior.
        return false;
    });
});

From jQuery documentation:

event.preventDefault()
If this method is called, the default action of the event will not be triggered.

Returning false is also a way to tell the event to not actually fire.

다른 팁

When you pushing F5 you are refreshing content of window received by last request. In your case it was POST sent to 'Account/Active' action. But I suspecting the data (content of textbox) was not sent at the second try.

Open network console of browser (for IE9 - press F12, go to Network tab and push 'Start capturing') and check body of request sent to server. I will not winder if data sending only on the first attempt.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top