0

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?

1
  • you should use preventDefault() - see w3schools.com/jquery/event_preventdefault.asp $('#generate-token').click(function (e) { e.preventDefault(); var token = Math.random().toString(36).slice(2); $("#token").val(token); }); Commented Nov 28, 2016 at 11:49

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.