Null reference from control after page loads - javascript

I am trying to run a piece of javascript after the page loads:
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (IsPostBack)
{
string controlName = getPostBackControlName();
if (controlName == "btnSubmit" || controlName == "ddlSalary")
{
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", "onLoadDisplay(this)", true);
}
}
}
Here is the referenced javascript:
function onLoadDisplay(sender) {
PerDiemClicked(sender);
}
function PerDiemClicked(sender) {
if (document.getElementById('<%= chkbxPerDiem.ClientID %>').checked == true) {
document.getElementById("PerDiemDisplay").style.display = 'inline';
}
else {
document.getElementById("PerDiemDisplay").style.display = 'none';
}
}
I'm getting this error:
0x800a138f - JavaScript runtime error: Unable to get property
'checked' of undefined or null reference
I dont understand why the checked is coming back null because I am waiting for the page to complete postback before checking. How do I check this control and run the above code correctly?
edit: here is the checkbox:
<asp:CheckBox ID="chkbxPerDiem" runat="server" Checked="false" onclick="PerDiemClicked(this)" />

Your script likely executed before chkbxPerDiem was added to the DOM. Perform your script in the window load event:
window.addEventListener("load", function() {
onLoadDisplay(this);
});
Try this:
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", #"
window.addEventListener('load', function() {
onLoadDisplay(this);
});", true);
See this answer

Here is how I solved it.
This code does in fact post after page load:
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (IsPostBack)
{
string controlName = getPostBackControlName();
if (controlName == "btnSubmit" || controlName == "ddlSalary")
{
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", "window.addEventListener('load', function() { onLoadDisplay(this); });", true);
}
}
}
I had to modify the javascript function to check if it exists before checking whether its checked:
function PerDiemClicked(sender) {
if (document.getElementById('<%= chkbxPerDiem.ClientID %>') != null) {
if (document.getElementById('<%= chkbxPerDiem.ClientID %>').checked == true) {
document.getElementById("PerDiemDisplay").style.display = 'inline';
}
else {
document.getElementById("PerDiemDisplay").style.display = 'none';
}
}
}
Thanks everyone.

Page_LoadComplete is a server-side event, and all server-side events will run before the page is even sent to the browser. Remember, these server-side events are related to constructing the page. You need to run your JavaScript after the page has been constructed, served, and fully loaded by the browser. This means the Page_LoadComplete event runs long before your JavaScript code can run.
Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", "onLoadDisplay(this)", true);
The code above registers a call to your JavaScript load function. But it will insert the call to that function at the top of your page. So it will run before the rest of the page is loaded.
You need to review how ASP.NET events work. Again, all of the server-side events run before the page is even sent to the browser. The JavaScript shouldn't run until after the browser has received and loaded the page.

Related

Server Sent Events: JavaScript events not working

I have written a small piece of code for generating server sent events and a corresponding JavaScript client to log all the messages. When i send the request, I can see in network tab of chrome that browser is receiving all the messages from server but in JavaScript only open event listener is triggered and message listener is never triggered. I have spent good amount of time on this without any success.
Here is my Java code which generates SSE:
#GET
#Path("/updates/sse")
#Produces(MediaType.SERVER_SENT_EVENTS)
public void publishUpdates(#Context SseEventSink sseEventSink) {
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
final OutboundSseEvent event = sse.newEventBuilder()
.name("message-to-client")
.data(String.class, "Hello world " + i + "!")
.build();
sseEventSink.send(event);
}
}).start();
}
Here is my JavaScript code to handle response:
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("/gra/services/updates/sse");
source.addEventListener('message', function(e) {
console.log("message");
console.log(e.data);
}, false);
source.addEventListener('open', function(e) {
// Connection was opened.
console.log("open");
}, false);
source.addEventListener('error', function(e) {
console.log("error");
console.log(e);
if (e.readyState == EventSource.CLOSED) {
// Connection was closed.
}
}, false);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
Here is what I get in console in chrome. Only open listener is invoked:
and here is what I can see in Network tab in chrome:
I am trying to figure out if browser is receiving the event data why message listener is not being invoked.
See the example in documentation for EventSource:
/* The event "message" is a special case, as it
* will capture events without an event field
* as well as events that have the specific type
* `event: message` It will not trigger on any
* other event type.
*/
sse.addEventListener("message", function(e) {
console.log(e.data)
})
Your message type is message-to-client, not "nothing".

Error: Unable to get property '_ScriptLoaderTask' of undefined or null reference

Why does Error: Unable to get property '_ScriptLoaderTask' of undefined or null referece get thrown when trying to close a RadWindow with ScriptManager and JavaScript in ASP? (Internet Explorer 11)
Our application has 'Save and Close' buttons that have the following C# code for the closing logic that is executed after the save has completed:
public void CloseWindow()
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "close",
"CloseModal()", true);
}
The .aspx page has the following JavaScript:
function CloseModal() {
var oWnd = GetRadWindow();
if (oWnd) {
oWnd.close();
}
}
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) {
oWindow = window.radWindow;
} else if (window.frameElement &&
window.frameElement.radWindow) {
oWindow = window.frameElement.radWindow;
}
return oWindow;
}
Adding setTimeout() for one second before the RadWindow .close() function is called seems to fix the issue. I believe this allows the ScriptManager.RegisterStartupScript just enough time to complete execution.
The following JavaScript is a solution to the problem, and stops the error modal from displaying post 'Save and Close' button click:
function CloseModal() {
var oWnd = GetRadWindow();
if (oWnd) {
setTimeout(function () {
oWnd.close();
}, 1000);
}
}

Redirect to a page after a pop up opens

I am trying to redirect a web page after a condition is returned as true but I can't seem to get it work. In theory this should, shouldn't it. What am I missing, is it even possible!
protected void btnVerify_Click(object sender, EventArgs e)
{
if (value == txtVerification.Text || txtVerification.Text == "****")
{
//defines a bool to tell if the popup window has been shown, this will only ever return true
bool PopupShown = doRedirect();
if(PopupShown)
{
Response.Redirect("somewebpage.aspx");
}
}
else
{
lblVerificationFailed.Visible = true;
}
}
//Opens the popup window to fire off the download and returns true
bool doRedirect()
{
string url = "GetDocs.aspx";
string s = "window.open('" + url + "', 'GetDocs', 'height=150,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
return true;
}
You are trying to do in the server things that can be much more easily done on the client side.
You're using a server event to catch the click of a button on your view, launch a client popup and later redirect your page execution.
Try with something like this on javascript:
var btnVerify = document.getElementById("btnVerify");
btnVerify.addEventListener("click", function() {
window.open('GetDocs.aspx', 'GetDocs', 'height=150,width=300,left=100,top=30,resizable=No,scrollbars=No,toolbar=no,menubar=no,location=no,directories=no, status=No');
window.location.href = "somewebpage.aspx";
});
Sussed it, if I use window.location.replace instead of window.location it works exactly like I want it to. Many thanks all :)

ClientScript not working properly on class C#

I want to deploy a script on C# which usually uses methods like:
ClientScript.RegisterStartupScript(GetType(), "script", "Details('" + hdnId.Value + "');", true);
However I wanted to make a class that runs that code:
public class WebUtilities
{
public static void CustomScript(Page objPage, string strScript)
{
objPage.ClientScript.RegisterStartupScript(objPage.GetType(), "script", strScript, true);
}
}
When I call WebUtilities.CustomScript, sometimes it works, but leaves a //]]> at the bottom of the page.
And there is one occasion that it does not work at all. I only noticed that the first method works, and the second one doesn't.
How can I make the class version to work properly?
I have this function, and it always works, try it
public static void callJavascriptFunction(string strScript)
{
if (HttpContext.Current == null && HttpContext.Current.Handler is Page) { return; }
Page currentPage = (Page)HttpContext.Current.Handler;
ScriptManager.RegisterStartupScript(currentPage,
currentPage.GetType(),
"Funct",
strScript,
true);
}

Javascript function and web service call synchronization

Hi i have this code in page_load event on aspx page:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FillSomeDropDownLists();
}
EnableExportButton(false);
if (!string.IsNullOrEmpty(Page.Request["__EVENTTARGET"]) && !string.IsNullOrEmpty(Page.Request["__EVENTARGUMENT"]) && Page.Request["__EVENTARGUMENT"] == "true")
{
ScriptManager.RegisterStartupScript(Page, GetType(), "Show", "ShowPopup();", true);
if (CallToWebService(Convert.ToInt32(Page.Request["__EVENTTARGET"]), 1))
{
SomeOtherCallToWebService();
Global.ShowMessage(this.Page, StringConstants.SUCCESS_TRANSACTION_TITLE);
}
else
{
Global.ShowMessage(this.Page, StringConstants.FAIL_TRANSACTION_TITLE);
}
ScriptManager.RegisterStartupScript(Page, GetType(), "Hide", "HidePopup();", true);
}
}
I would like to show a javascript popup, then do webservice related stuff, and then hide the popup. That is how I coded it.
But in page execution I get call to webservices first, and then shows and hides the popup. Showing and hiding the popup is so fast that it seems nothing happens.
Is there solution to get what I want?

Categories

Resources