jQuery function not working in MVC Partial View [duplicate] - javascript

This question already has answers here:
Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine
(23 answers)
Closed 5 years ago.
The .hide function in my partial view is not rendering for second and third person initially, then the delay .hide and .fadein will not work either. I am new to js and jquery so I am probably missing something obvious... Why would this js script not be working inside of a partial view?
Everything works when it is all in the main view, but the reason I need a partial view is because I do not want to reload the entire page every 15 seconds. I have done some research and there might be something wrong with getting an html data type?
Main View:
#model IEnumerable<project.Models.MyList>
<div id="scrolllist">
#Html.Partial("_ScrollList")
</div>
#section Scripts{
<script>
function loadScrollListPV() {
$.ajax({
url: "#Url.Action("ScrollList")",
type: 'GET', // <-- make a async request by GET
dataType: 'html', // <-- to expect an html response
success: function(result) {
$('#scrolllist').html(result);
}
});
}
$(function() {
loadScrollListPV();
// re-call the functions each 15 seconds
window.setInterval("loadScrollListPV()", 15000);
});
</script>
}
Controller Action:
public ActionResult ScrollList()
{
return PartialView("_ScrollList", db.MyList.ToList());
}
Partial View:
#model IEnumerable<project.Models.MyList>
<div id="firstperson">
#*Get lastest record and display.*#
#foreach (var donor in Model.OrderByDescending(p => p.ProcessTime).Take(1))
{
}
</div>
<div id="secondperson">
#*Get second lastest record and display.*#
#foreach (var donor in Model.OrderByDescending(p => p.ProcessTime).Skip(1).Take(1))
{
}
</div>
<div id="thirdperson">
#*Get third lastest record and display.*#
#foreach (var donor in Model.OrderByDescending(p => p.ProcessTime).Skip(2).Take(1))
{
}
</div>
#section Scripts{
<script>
$("#secondperson").hide();
$("#thirdperson").hide();
function person() {
$("#firstperson").delay(5000).hide(0, function () {
$("#secondperson").fadeIn();
$("#secondperson").delay(5000).hide(0, function () {
$("#thirdperson").fadeIn();
$("#thirdperson").delay(5000).hide(0, function () {
$("#firstperson").fadeIn();
person();
});
});
});
}
</script>
}
Any help would be awesome and thanks in advance!

I am not 100% sure here, but I think there may be a problem with rendering the #script section in partial views according to this answer. It is mentioned that Partial Views are not able to use the #section element by default.
Try removing the razor syntax around the script section and just use:
<script type="text/javascript">
$("#secondperson").hide();
$("#thirdperson").hide();
function person() {
$("#firstperson").delay(5000).hide(0, function () {
$("#secondperson").fadeIn();
$("#secondperson").delay(5000).hide(0, function () {
$("#thirdperson").fadeIn();
$("#thirdperson").delay(5000).hide(0, function () {
$("#firstperson").fadeIn();
person();
});
});
});
}
</script>

1) Remove the #section Scripts{ and your code will work.
2) You should avoid the callback hell of hide() and fadeIn(). If there are 10 divs, you'd have to add 10 layers of that code. The below approach would work with any number of divs in your partial view:
You can assign your divs a class. Make only the first div visible by default. Create a function which will be called every 5 seconds.
// gets the currently visible div. Hides it.
// If this is last content `div`, shows the first div, else shows the next div
function incremental() {
$visible = $(".content-div:visible");
$visible.hide();
$visible.next().is('.content-div')
? $visible.next().fadeIn()
: $(".content-div").first().fadeIn();
}
setInterval(incremental, 3000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content-div">first content</div>
<div class="content-div" style="display:none">second content</div>
<div class="content-div" style="display:none">third content</div>
This partialIntervalRef variable will be defined in the global scope (Main View). And every time before loading your partial view, you should clear it.
<script>
var partialIntervalRef;
function loadScrollListPV() {
clearInterval(partialIntervalRef);
-----
----
}
This is much more cleaner and extensible than the using the callbacks.
3)window.setInterval("loadScrollListPV()", 15000) should be changed to window.setInterval(loadScrollListPV, 15000)

You can't call a section from within a partial view. You can call it as an action with Layout = null; to achieve a similar result.

Related

Call HelperResult from javascript function

I have a treeview on a view in mvc and when a user clicks one of the items I want to load a partial view to the right of the main treeview
I have a a helperresult inside a div that should load the view, but when I call it like this it just freezes the treeview and I cannot click any items.
Here is what I am trying
#helper RenderFirst()
{
<div class="treeview-back">
#Html.Action("Results", "Results");
</div>
}
</div>
</body>
</html>
</div>
<script>
var treeview;
var siteSelect = "Result1";
function onSelect(e) {
if (this.text(e.node) == siteSelect) {
#RenderFirst();
} else {
alert('false');
}
}
$(document).ready(function() {
treeview = $("#treeview").data("kendoTreeView");
});
</script>
if i replace #RenderFirst(); with this alert('true') it is fine.
I am using ASP.NET MVC4 with VS 2012 C#
Thanks for any help.
You're mixing server-side code with JavaScript which can't work. You should either use jQuery to insert the div element or render it when loading the page (make it invisible initially), then in onSelect:
$(".treeview-back").show();

Linking button to jQuery through service

I have a small problem that should be very easy to overcome. For some reason I cant work this out. So the problem is I cannot get a button to link to some jquery. My set-up is as follows (showing the relevant code):
Default.aspx
jQuery:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
});
}
jQuery(document).ready(function () {
getContent();
});
HTML:
<div id="content"></div>
ContentService.vb
<WebMethod()> _
Public Function GetContent(number As Integer) As String
Dim sb = New StringBuilder
sb.AppendLine("<table>")
sb.AppendLine("<tr>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Number</td>")
sb.AppendLine("</tr>")
sb.AppendLine("<tr>")
sb.AppendLine("<td>" & number & "</td>")
sb.AppendLine("<td><a href='#' id='test' class='fg-button ui-state-default ui-corner-all'><img src='" & Context.Request.ApplicationPath & "/images/spacer.gif' class='ui-icon ui-icon-pencil' /></a></td>")
sb.AppendLine("</tr>")
sb.AppendLine("</table>")
Return sb.ToString
End Function
So that's the basics of what I have everything works but I'm not sure how to get the a button (id='test') to get linked to some jQuery. I want it to be pressed and bring up a popup.
I have tried to put the jQuery on default.aspx but this doesn't seem to work unless the button is place in the HTML on that page.
$('#test').unbind('click').click(function () {
alert('Working');
});
I'm sure this is easy to do, but I have been trying for a while and cannot seem to get it to work.
Is the problem that you're trying to bind to the element that ISN'T in existance yet?
are you calling the $('#test').unbind('click').click(function () {
alert('Working');
}); BEFORE the service has returned?
$('#test').on('click', function () {
alert('Working');
});
This will bind the event to the '#test' element once it has been inserted in to the DOM.
As you load the content via ajax, you have to bind to $('#content'). Like this:
$(function () {
$('#content').on('click', '#test', function () {
e.preventDefault(); // if a default action is not needed needed
alert('Working');
});
});
I guess this is about not preventing the default behaviour of the A href tag. Now it will probably link to '#' instead of firing the onclick event.
$('#test').on('click', function (e) {
alert('Working');
e.preventDefault();
});
You could try to wrap this in a document ready, or eventually use the .on binder from jQuery, since it's dynamic content.
Solved
It was a very small thing that caused this. The code to fix this problem is as follows:
$('#test').unbind('click').click(test);
This needed to go inside the function with the json so:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
$('#test').unbind('click').click(test);
});
}
Thank you to everyone that has tried to help me.

Trouble calling JavaScript function on page load

I have a javascript function that i have named refreshProjects(), what it does is filter a dropdownlist depending on what was selected in a previous dropdownlist. But i need to also filter my list direcktly after the page has finishd loading.
I have tried using the code window.onload = refreshProjects(id) with no sucsses, but onload workes when i use window.onload = alert('This page has finished loading!'), so i know that part off the script works. So how do i call a javascript function on load, i thought that it would be simple but evrything i tried have failed.
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
window.onload = refreshProjects(id); <-- Problem
$("#ddCustomers").change(function () {
refreshProjects($(this).val());
});
function refreshProjects(id) {
var projects = $("#ddProjects");
$.get('#Url.Action("FilterProjects","TimeEntry")', { customerId: id },
function (result) {
// clear the dropdown
projects.empty();
//Add a deafult "null" value
$("#ddProjects").get(0).options[0] = new Option("[ - No project - ]", "-1");
// rebuild the dropdown
$.each(result, function (i, e) {
projects.append($('<option/>').text(e.Text).val(e.Value));
});
});
}</script>
}
This is for MVC 4.5.
Try changing window.onload = refreshProjects(id); to:
window.onload = function() { refreshProjects($("#ddCustomers").val()); };
Onload expects a callback function. You were directly executing refreshProjects() and setting the return value as the onload.
But since you seem to be using jQUery, you could do the following:
$(function() {
refreshProjects($("#ddCustomers").val());
});
This will execute refreshProjects when the document is ready (which actually is before window load).
You can also try to use the following:
$(document).ready(function () {
refreshProjects(id);
});
This should work aswell if you are using jQuery.

Javascript: Detect load in ascx page. Internet Explorer

I have a dropdown that will trigger the ChangeGraph javascript function. In Chrome/Firefox, when my partial view (.ascx) is loaded, I get the hello alert. This is not the case in IE. Any ideas on how to solve this. Basically I can't initiate a javascript function once the ascx page is written using "$('#GraphForm').html(data);"
From my Index.aspx:
<div id="GraphForm"></div>
Javascript:
function ChangeGraph(displayTypeId) {
$('#GraphForm').html("");
$.get('/Dashboard/GetGraphForm', { id: displayTypeId }, function(data) {
$('#GraphForm').html(data);
});
}
Controller:
public PartialViewResult GetGraphForm(int id)
{
//... Build Model (removed)
return PartialView("EnergyConsumedFormView"/* , model */);
}
EnergyConsumedFormView.ascx Javascript:
<script type="text/javascript">
$(document).ready(function() {
alert('hello');
});
</script>
I'm new to javascript so the answer wasn't obvious until I figured it out. Know it seems REAL obvious. Just call the function if you don't care if the document is ready...
<script type="text/javascript">
alert('hello');
</script>

The javascript code from server side is not working in asp.net?

i am developing an Asp.net application when i call javascript function from codebehind i found that for example:
click event not fired
i have a javascript function that fill the dropdown list with items using ajax but when page loaded i found dropdown list empty
i am using RegisterClientScriptBlock to execute the javascript code
so is there any solution for these problems?
code snippet:
code behind:
ClientScript.RegisterClientScriptBlock(this.GetType(), "ClientBlock", javacode.ToString());
this what in javacode variable :
<script type="text/javascript">
<!--
function ExecuteScript()
{
$("#divGender input").click();
GetDMspecifyList(5);
$("cp1_drpDMSpecify").removeAttr('disabled');
$("cp1_drpDMSpecify option:selected").val(4);
$("#divFamily input").click();
}
</script>
// -->
this the function used to fill dropdown list but it is not working
function GetDMspecifyList(DMID) {
$("#DMLoader").show();
$.getJSON('FillDropDownLists.aspx?DMTypeID=' + DMID, function (types) {
$.each(types, function () {
$("#cp1_drpDMSpecify").append($("<option></option>").val(this['DMTypeCode']).html(this['DMTypeName']));
});
$("#DMLoader").hide();
$("#DMSpecify_span").show();
$("#cp1_hdDMType").val($("#cp1_drpDMSpecify").val());
$("#cp1_drpDMSpecify").removeAttr('disabled');
});
}
First of all the function "ExecuteScript()" is lacking it's closing curly brace "}".
Also, is the ExecuteScript() function called anywhere?
EDIT
You could try something similar to the code below :
<script type="text/javascript">
<!--
function ExecuteScript() {
$("#divGender input").click();
GetDMspecifyList(5, function() {
$("cp1_drpDMSpecify").removeAttr('disabled');
$("cp1_drpDMSpecify option:selected").val(4);
$("#divFamily input").click();
});
}
function GetDMspecifyList(DMID, callback) {
$("#DMLoader").show();
$.getJSON('FillDropDownLists.aspx?DMTypeID=' + DMID, function (types) {
$.each(types, function () {
$("#cp1_drpDMSpecify").append($("<option></option>").val(this['DMTypeCode']).html(this['DMTypeName']));
});
$("#DMLoader").hide();
$("#DMSpecify_span").show();
$("#cp1_hdDMType").val($("#cp1_drpDMSpecify").val());
$("#cp1_drpDMSpecify").removeAttr('disabled');
callback();
});
}
$(function() { ExecuteScript(); });
// -->
</script>

Categories