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 '&'".
CodePudding user response:
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.