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.