简体   繁体   中英

How to open modal popup without button click in .net core MVC

I have a custom modal popup that displays a message if the data that was entered in the view does not match the requirements etc an entered medicine does not suit for the person that the medicine was described to. Here is my code for the script:

$(document).ready(function () {
    $("#btnShowModal").click(function () {
        $("#loginModal").modal('show');
    });

    $("#btnHideModal").click(function () {
        $("#loginModal").modal('hide');
    });
});

This handles well the instances where I want to open the popup with a button click, but I would like it to be opened when a certain condition is filled, for example:

<script type="text/javascript">
    function openPopup() {
        $("#loginModal").modal('show');
    }
    @if (afterError)
    {

        @:openPopup();
    }
</script>

This does not work however, how should I handle this?

Your JavaScript function definition will work just fine, but your function is not being called because of your razor C# code. If that is meant to be C# code than it's not valid, you have to explicitly check for true & false values. In JavaScript your can just simply equate truthy and falsy values the way that you did it in your original post...

example...

if (someCondition) is valid in JavaScript but not C#.

<script type="text/javascript">
    function openPopup() {
        $("#loginModal").modal('show');
    }

    @if (afterError != null)
    {

        openPopup();
    }
</script>

Also keep in mind your logic is only called once on page load. You can fire off that function from any event though... mouseclick, mouseenter etc...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM