Reputation:
Problem: partialview contains js scripts, when they are first loaded, they work. After the second loading, js scripts stop working.
Desc: I have partial view reload on value change on selectbox (this calls this function)
@(Html
.DevExtreme()
.SelectBox()
.ID("id_sb_year")
.DataSource(d => d
.Mvc()
.Controller("Ecp")
.LoadAction("WezRok")
.Key("Rok")
)
.DisplayExpr("Rok")
.ValueExpr("Rok")
.SearchEnabled(true)
.OnValueChanged("pobierzTabele")
)
@(Html
.DevExtreme()
.SelectBox()
.ID("id_sb_month")
.DataSource(d => d
.Mvc()
.Controller("Ecp")
.LoadAction("WezMiesiac")
.Key("Miesiac")
)
.DisplayExpr("DescMiesiac")
.ValueExpr("Miesiac")
.SearchEnabled(true)
.OnValueChanged("pobierzTabele")
)
Two values from two selectboxes must be selected for the function to work
function pobierzTabele() {
var numerMiesiaca = $("#id_sb_month").dxSelectBox("instance").option("value")
var numerRoku = $("#id_sb_year").dxSelectBox("instance").option("value")
if (numerMiesiaca != null && numerRoku != null) {
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
var liczbaDni = daysInMonth(numerMiesiaca, numerRoku);
var userDate = {
numerMiesiaca: $("#id_sb_month").dxSelectBox("instance").option("value"),
numerRoku: $("#id_sb_year").dxSelectBox("instance").option("value"),
liczbaDni: liczbaDni
};
$.ajax({
url: "@Url.Action("PartialTabelaEcp", "Home")",
type: "POST",
dataType: "html",
data: {"userDate": JSON.stringify(userDate)},
cache: false,
success: function (data) {
$("#kartaEcp").html(data);
},
failure: function (error) {
alert(error);
},
error: function (error) {
alert(error);
}
});
}
}
effect: throws this partialview in this place
<div class="kartaEcp" name="kartaEcp" id="kartaEcp">
</div>
partial view:
@using AppEcp.Models
@model ParentView
@using (Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "tableForm" }))
{
<table><table>
}
<script src="~/js/tabela/Arkusz.js"></script>
<script src="~/js/tabela/halfStartEnd.js"></script>
<script src="~/js/tabela/minimumEnds.js"></script>
Nowadays: I need to refresh the page to be able to select the value again and load the partialview again, which is unacceptable
I found sth this https://api.jquery.com/on/
but I dont know how to use it :/
Upvotes: 1
Views: 1453
Reputation: 2370
When you evoke .html() to replace partial view content, you are actually replacing existing DOM elements with new one. As a result, event handlers attached to these elements are also removed and your code stops working.
You will have to re-assign event handlers. Use .on() function to do so. A better approach is to use delegated event handlers inside parent view. But you can achieve results with below trick.
Update your 'success' function as below,
$("#kartaEcp").html(data);
$( "#id_sb_year" ).on( "change", function() {
pobierzTabele();
});
$( "#id_sb_month" ).on( "change", function() {
pobierzTabele();
});
Upvotes: 1