1

I'm using ASP.NET Core, and I have a modal which is opened from Partial view like this:

<button type="button" class="btn btn-primary" data-toggle="modal" id="OpenModal">Create Lines</button>
<div class="modal fade" id="AgreeModal" tabindex="-1" data-url='@Url.Action("OpenModal","RequestApproval")' aria-hidden="true">
    <div class="modal-dialog modal-lg" id="ShowModal">
    </div>
</div>

The partial view

@model IEnumerable<RequestCreateLineViewModel>

<div class="modal-content">
    <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <div class="modal-body">
        <button class="btn btn-primary" type="button" onclick="testButton()">test</button>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
    </div>
</div>

Test button function

$(document).ready(function () {
    function testButton() {
        console.log("here");
    }
})

But I don't know why when I click the button on the modal (testButton onclick event), it's always return testButton is not defined. TestButton function is a script in parent view. Please help, thanks in advance.

Huệ Vũ
  • 35
  • 7
  • The **scope** of `testButton` is limited to the inside of the anonymous callback function inside `ready()`. You need to make it a top-level function. Also, **STOP USING JQUERY IT'S 2021 ARGGHGHHHH!!!** – Dai Jun 09 '21 at 06:49
  • How can I make it a top-level? I'm a fresher in ASP.NET, so I use JQuery, it's easy to use – Huệ Vũ Jun 09 '21 at 06:56

1 Answers1

0

".ready()" is a function to be executed when the DOM is fully loaded.

  • In other words, execute the required function or method in it.
  • For example:

$(document).ready(function () {
        test();
    });
function test() {
   alert("hello");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You just need to modify your code like this:

<script>
    $.ajax({
        url: "@Url.Action("partialviewtest", "Test")",
        type: "GET",
        success: function (data) {
            $("#ShowModal").html(data);
            $("#AgreeModal").modal("show");
        }
    });
    function testButton() {
        console.log("here");
    }
</script>

enter image description here

Yihui Sun
  • 755
  • 3
  • 5