I am new to web development and I am using .net core MVC with VS2017, and trying to load several partial views inside a div (section1 and section2) using ajax and javascript.
My index page:
<div>
<a asp-action="setupprogram" asp-controller="Setup" data-target="Section1" class="section1">Setup Programs</a>
</div>
<br />
<div id="Section1"></div>
<br />
<div id="Section2"></div>
<br />
When I include the javascript code inside the chtml it run perfectly, but when I remove the jQuery code and put it inside site.js
, it didn't work
My site.js code:
$(document).ready(function () {
$("#Sform").submit(function (e) {
e.preventDefault();
var urlsx = $('#UrlsX').val();
var urls = $('#Urls').val();
$.ajax({
url: urls,
type: "POST",
dataType: "html",
data: $('#Sform').serialize(),
success: function (data, textStatus, xhr) {
$('#Section2').html(data);
$("#Section1").load(urlsx)
},
error: function (xhr, textStatus, errorThrown) {
$("#Section2").html(xhr.responseText);
}
});
});
$('.section1').click(function (e) {
e.preventDefault();
$("#Section1").show();
$('#' + $(this).data("target")).load($(this).attr("href"));
});
$('.section2').click(function (e) {
e.preventDefault();
$("#Section1").show();
$("#Section2").show();
$('#' + $(this).data("target")).load($(this).attr("href"));
});
});
the simple way to solve this issue is to include the script tag
<script src="~/js/site.js"></script>
at each partial view to load the JavaScript code after the DOM load and to be able to find the required objects, accounting to this post and also this post
Mmy problem is that the JavaScript code make the page load time too long after few clicks and it themes that the code is looping inside my C# action several times and making the page load time unaccepted.
Also the second partial view do not recognize the code and load in a new page rather than being rendered in the Section2 div.
The site.js
file is referanced in the _Layout.cshtml
:
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js"></script>@*asp-append-version="true"*@
</environment>
The first patial view that load in section one is as follwoing :
@foreach (var p in Model)
{
<div>
@p.ProgName
<a asp-action="setupprogramEdit" asp-controller="Setup" asp-route-id="@p.ProgID" data-target="Section2" class="section2">Edit</a>
|| <a asp-action="setupprogramdelete" asp-controller="Setup" asp-route-id="@p.ProgID" data-target="Section2" class="section2">Delete</a>
</div>
}
<div>
<a asp-action="setupprogram" asp-controller="Setup" data-target="Section1" class="cancel2">cancel</a>
</div>
First : is it better to keep the JavaScript code inside the chtml view page ?\
Second : any idea how to come over this issue, in case i decided to move the JavaScript code into a separate file ?