Giobbo Giobbo - 6 days ago 6
ASP.NET (C#) Question

ASP.NET Button click call Javascript function in BeginForm and stop form submit

I have this situation:

@using (Html.BeginForm("CreateNewApplication", "Token", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="app-name" class="op-form op-label">Application:</label>
@Html.TextBoxFor(a => a.appName, new { @placeholder = "Nome dell'applicazione", @class = "op-form op-text app-name" })<br />
<label for="token" class="op-form op-label">Token:</label>
<button id="generate-token" class="op-form" value="Genera Token">Generate Token</button>
@Html.TextBoxFor(a => a.appToken, new { @placeholder = "Token", @id = "token", @class = "op -form op-text token" })<br />
<input id="submit" type="submit" class="op-form op-submit" value="Submit" />
}


and the button call this Javascript function:

$('#generate-token').click(function () {
var token = Math.random().toString(36).slice(2);
$("#token").val(token);
});


The problem is that when click the button, the Javascript function is correctly called, but also is called the CreateNewToken method in my Token controller. While I want only call Javascript on click button and call method controller when click submit.
Is possible to do? How?

Answer

Problem:

Inside a "form" element the default behaviour of a button when type is not mentioned is "submit"

hence your form is getting submitted as soon as you click the button.

Solution: Add the type="button" attribute into your button element.

<button id="generate-token" type="button" class="op-form" value="Genera Token">Generate Token</button>

Source http://www.w3schools.com/tags/tag_button.asp

Comments