Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

Bootstrap script not working in Blazor application

I want to use Bootstrap forms custom styles for a form. As I can't add script in the razor file I have added it to the _Host.cshtml file instead. But it looks like it never is executed. The form don't give any errors.

Any idea how to solve this issue?

_Host.cshtml file

<script>
    // Example starter JavaScript for disabling form submissions if there are invalid fields
    (function () {
        'use strict'

        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.querySelectorAll('.needs-validation')

        // Loop over them and prevent submission
        Array.prototype.slice.call(forms)
            .forEach(function (form) {
                form.addEventListener('submit', function (event) {
                    if (!form.checkValidity()) {
                        event.preventDefault()
                        event.stopPropagation()
                    }

                    form.classList.add('was-validated')
                }, false)
            })
    })()
</script>

razor file

<form id="registerform" class="needs-validation" novalidate>
            <div class="form-group">
                <label for="firstname">First name</label>
                <input type="text" class="form-control" id="firstname" required>
            </div>
            // some more inputs here...
            <button id="btnRegisterSubmit" type="submit" class="btn btn-primary">Submit</button>
 </form>
question from:https://stackoverflow.com/questions/65561008/bootstrap-script-not-working-in-blazor-application

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use the blazor validation, you can change styles and classes conditionally (by using an EditContext you can get the validity of forms and fields in your own code). Maybe there is even a nuget package that wraps this.

Of you still want to go with js, use a named function and initialise your form from the first render (OnAfterRenderAsync)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...