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?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.