Submit button doenst work with script asp.net mvc5

I have a maybe simple problem but I don`t have that much experience with scripts:

I have this Skript in my _Layout.cshtml:

<script>
    $('button').click(function () {
        $(this).prop('disabled', true);
    });
</script>

and one of my views:

@using (Html.BeginForm("Create", "Home", FormMethod.Post, null))
{
    @Html.AntiForgeryToken()

    <div class="mt-5 d-flex flex-row">
        <textarea class="form-control" name="TextArea"></textarea>

        <button class="btn btn-secondary btn-block mt-2 post-btn" type="submit" id="PostButton">Post</button>

    </div>
}

This form works great without the script, but for any reason with the script it doesn`t work.

I placed the script in the _layout.cshtml because I want to have it for all buttons in my asp.net page.

After click on the button the button is disabled - as I wish - but the action result "Create" in the HomeController will not called.

I think I need to extend the script but can someone help me how to do it?

Thanks all

1 answer

  • answered 2021-02-27 03:50 Nayem_43

    If I'm getting your question correctly, you are messing up with the submit form and making the button disable. Without the script, the form works correctly as the button is submitted type and not disabled. But with the script, as soon as you click the button it becomes disabled, and the form can't be posted. So use this script instead of yours;

        $('#mainForm').submit(function (e) {
            $('#PostButton').prop('disabled', true);
        });
    

    And also make a little bit of change in your form declaration;

    @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { @id = "mainForm"})) { @Html.AntiForgeryToken()

    <div class="mt-5 d-flex flex-row">
        <textarea class="form-control" name="TextArea"></textarea>
        <button class="btn btn-secondary btn-block mt-2 post-btn" type="submit" id="PostButton">Post</button>
    </div>
    

    }