Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Asp.Net-Core pass JavaScript function to partial view

Using asp.net-core I made a "PopUp.cshtml" file:

<div class="popUpDeleteBackground" hidden>
    <div class="popUpDelete">
        <h3>Are you sure you want to delete this?</h3>
        <p>This action is irreversible</p>
        <div class="popUpDeleteButtonDiv">
            <button class="btn deleteConfirm">JA</button>
            <button class="btn" onclick="PopUpRemove()">NEE</button>
        </div>
    </div>
</div>
<script>
    function PopUpShow(licensePlate) {
        $(".popUpDeleteBackground").attr("hidden", false);

        $(".deleteConfirm").on("click", () => {
            Delete(licensePlate);
            PopUpRemove();
        });
    }
    function PopUpRemove() {
        $(".popUpDeleteBackground").attr("hidden", true);
    }
</script>

I want this popup partial to be used in multiple pages of the website. The problem is that the delete functions are different for each page.
So my question is: Is there a way to pass a JavaScript function to a partial view?

What I’ve tried so far is passing a string with @await Html.PartialAsync("_ConfirmPopUp", "functionToRun()"); and then tried to run it with <script>@Model</script>.
But I got an error message in the console saying: "Uncaught SyntaxError: Unexpected token ‘&’".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are passing functionToRun() as a string to the Model of the view. Instead just pass the name of the function without the parenthesis – functionToRun.

Then in the code dont write <script>@Model</script>. Instead just put the name of the calling function dynamically when the page loads like this:

<script>
    function PopUpShow(licensePlate) {
        $(".popUpDeleteBackground").attr("hidden", false);

        $(".deleteConfirm").on("click", () => {
            //Delete(licensePlate);
            @string.Format("{0}();", Model)
            PopUpRemove();
        });
    }
    function PopUpRemove() {
        $(".popUpDeleteBackground").attr("hidden", true);
    }
</script>

This will render the name of the function that would be called on click of the .deleteConfirm element. Note the @string.Format("{0}();", Model) code instead of the Delete function call.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading