0

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 '&'".

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I get the error "Uncaught SyntaxError: Unexpected token '<'" when using <text>@Model + "();"</text>.
I have updated the code. This is a cleaner version and less error-prone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.