Javascript: Detect load in ascx page. Internet Explorer - javascript

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>

Related

jQuery function not working in MVC Partial View [duplicate]

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.

Why doesn't function get called on first page load, only after refreshing?

I've searched, but I could not find the solution to this problem. For some reason function doesn't get called when page loads the first time, only after refreshing the page it gets called. Examples:
function init() {
alert("hello");
}
Either calling the function with following method:
$(window).load(function () {
init();
});
Or inside a body tag:
<body onLoad="init()">
Also, this problem doesn't occur when I open page directly, only when I'm being linked to the page from another page.
Solved, mobile options must be set before loading jquery.mobile.
<script language=javascript>
$(document).bind("mobileinit", function () {
$.mobile.ajaxLinksEnabled = false;
$.mobile.ajaxEnabled = false;
});
</script>
<script src="scripts/jquery.mobile-1.2.0.js"></script>
Try something in the lines of:
function init() {
alert('Hello!');
}
window.onload(function() {
init();
}

Call function created in view using javascript in the same view

I have created a view which contains both Javascript and functions as shown:
#functions
{
public int DaysInMonth(string Month)
{
//code to get the no of days in month;
}
}
I have drop down list that contains month..
Now I want to write code on dropdownlist's change event using jQuery which will call the above function.
<script type="text/javascript">
$(function () {
$('#Months').live('change', function () {
//code to call the above function
});
});
</script>
Here ('#Months') is the id of the dropdownlist..
Note: Both the above code snippets are in the same view (Index).
How can i link the above two code snippets??
Thank you..
#functions
{
public int DaysInMonth(string Month)
{
//code to get the no of days in month;
}
}
try like this
<script type="text/javascript">
#DaysInMonth(month);
</script>
it worked fine in my program.
Try this:
/*#cc_on #*/
<script type="text/javascript">
$(function () {
$('#Months').live('change', function () {
var monthSelected = $(this).val();
//code to call the above function
#DaysInMonth(monthSelected);
});
});
</script>
More info on this is at:
http://www.mikesdotnetting.com/Article/173/The-Difference-Between-#Helpers-and-#Functions-In-WebMatrix
Also have a look at this answer:
JavaScript Error: conditional compilation is turned off in MVC2 View

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>

Js javascript code problem

Hi i have a problem with my js code. So, i include in 'head' in my site, script
var Engine;
jQuery
(
function($)
{
Engine =
{
utils :
{
site : function(id)
{
$('#content').html('<strong>Please wait..</strong>').load('engine.php',{'site':id},function()
{
os = {adres:'drugi'};
history.pushState(os,'s',ts);
}
);
},
topnav : function()
{
$('div li').bind('click',function()
{
Engine.utils.site($(this).attr('rel'));
unbind('click',false);
}
);
}
}
};
Engine.utils.topnav();
}
);
Now i want call included script in index.php
<script language="JavaScript" type="text/javascript">
Engine.utils.site(1);
</script>
And here is a problem above code doesn't works.
But if i click on any 'li' element Engine.utils.site work's correctly.
Please help me i try fix it a few days.
Sory for my bad english
Have you tried putting the call in a ready function?
<script language="JavaScript" type="text/javascript">
$(function() {
Engine.utils.site(1);
});
</script>
This happens because of closure. Your object Engine is not visible outside anonymous function

Categories