Show Image/HTML before Page_Load is completed - asp.net

I have following code in aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="test.aspx.vb" nherits="test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"></head>
<body>
<img src="images/loading_anim.gif" />Please wait...
</body>
</html>
In test.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
......Do some processing here .
Response.redirect("Next.aspx")
End Sub
Code Behind I do some processing in Page_load method and redirect to other page but it might take some time so I want to show user loading image.But it shows that after page_load is completed.How to handle this ?

I will suggest that you use a generic handler (ashx) and use un-buffered response. For example:
public class Handler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.BufferOutput = false;
context.Response.Write("<html><head></head><body><img src=\"images/loading_anim.gif\" />Please wait...</body></html>"
context.Response.Flush();
// do your processing
...
// redirect
}
...
}
Yet another way to first show image on the client side (using java-script) and then do redirection (or post) from client side.

I don't think it will work because always the server side code works first, then only HTML rendering starts. Better option will be using Ajax.
More details here : ASP.NET Integration with IIS 7

Related

What's the difference between script function and code behind function?

<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' The first time the page loads,
' render the DefaultView.
If Not IsPostBack Then
' Set DefaultView as the active view.
MultiView1.SetActiveView(DefaultView)
End If
End Sub
Sub LinkButton_Command(sender As Object, e As System.Web.UI.WebControls.CommandEventArgs)
' Determine which link button was clicked
' and set the active view to
' the view selected by the user.
Select Case (e.CommandArgument)
Case "DefaultView"
MultiView1.SetActiveView(DefaultView)
Case "News"
MultiView1.SetActiveView(NewsView)
Case "Shopping"
MultiView1.SetActiveView(ShoppingView)
Case Else
Throw New Exception("You did not select a valid list item.")
End Select
End Sub
</script>
what is difference between above code in(aspx) And if the same code in code behind(aspx.cs). Difference between function defined in tag with runat="server" attribute and function defined in code behind...?
How to execute JavaScript Function From ASP.NET Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="How_calljavascript_aspx_page.aspx.cs" Inherits="How_calljavascript_aspx_page" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Call JavaScript in asp.net page by C# on page load </title>
<script type="text/javascript">
function MyFunction() {
alert('this is javascript function run by C# code.');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
execute JavaScript from code behind in asp.net:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class How_calljavascript_aspx_page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"alert", "MyFunction();", true);
}
}
}
Functionally there is no difference between these two approaches, both will work the same for you.
Page script is useful if you have a small server side code, so that you can embed that code in the page itself.
But this will make things messier if the code is large.
The page designers will have access to the page code here.
The code behind approach provides you a clear separation of HTML and asp or VB code. Thats all...no functional difference between two approaches.

Apparently odd ASP.NET Page Behaviour... might just be newbie error?

I'm new to ASP.NET but have quite a few successful test pages going now which I am using to slowly build up a new website and data application... hence my many questions on here.
Anyway, in my efforts to understand JSON, I have a test page trying to get the data out, but for some reason the script works fine when it's all one page, but not as code behind.
My ASPX file is:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="json.aspx.vb" Inherits="jsonPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form runat="server">
Output:
<div id="readOut" runat="server"></div>
</form>
</body>
</html>
Code behind:
Imports Jayrock.Json.JsonTextWriter, Jayrock.Json, Jayrock.Json.Conversion, System.Net
Partial Class jsonPage
Inherits System.Web.UI.Page
Sub Page_Load(Sender As Object, E As EventArgs)
Dim cMessage As String = "{""ID"": 8291, ""Item"": ""Epiphone Les Paul Tribute Plus Outfit"", ""Main Image"": ""8291-113247"", ""Colour"": ""Vintage Sunburst"", ""Option"": ""none"", ""Price"": 549.0}"
Dim objResponse As JsonObject = CType(JsonConvert.Import(cMessage), JsonObject)
readOut.InnerText = "Item name is: " & objResponse("Item")
End Sub
End Class
As I say, this is just a test code to try to get to grips with JSON, the text "Item name is:" followed by the result of the JSON parsing, should be posted into the div id="readOut" in the main ASPX page, but it won't... the strange thing is that it works is I take out the Page_Load sub and run the code in the head of the ASPX file.
I've tried comparing this to other files I have that are working and can find no obvious reason why this is happening.
I think this may be your problem. I suspect you weren't even able to hit that code with a breakpoint?
Page_Load(Sender As Object, E As EventArgs)
Should have a handles clause.
Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

How to get Page.ClientScript.RegisterClientScriptInclude to include in the head?

The included script references, in particular jQuery, are being rendered after viewstate. Is there a way to get this in the < head>?
Page.ClientScript.RegisterClientScriptInclude("jQuery", "/scripts/jquery.js");
I am trying to register jquery.js in a user control's page load.
Thanks in advance!
P.S. If it can't be done (with ClientScript), anyone have an idea why they didn't build it in?
UPDATE
The main feature of the ClientScript manager I need is the ability to only include a script once. The control can appear many times on a page, but i only want one jQuery script include
to directly inlcude it in the HEAD:
HtmlGenericControl Include = new HtmlGenericControl("script");
Include.Attributes.Add("type", "text/javascript");
Include.Attributes.Add("src", sInclude);
this.Page.Header.Controls.Add(Include);
you would want to check to make sure its not there already before adding it.
I had this problem a while back, and I ended up not using RegisterClientScriptInclude.
I placed a placeholder in the header of the page, and added the script tag to the placeholder via a HtmlGenericControl.
I'll see if I can find my code and I'll edit my answer with it.
EDIT
I couldn't find my code, so I just re-created it:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<asp:PlaceHolder runat="server" ID="HeadPlaceHolder"></asp:PlaceHolder>
</head>
<body>
...
</body>
</html>
And the Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
HeadPlaceHolder.Controls.Add(/* Your control here */);
}
Hey, old question, but maybe this is still of interest for someone.
I am creating a own UserControl with .net 3.5sp1, ran into the same problems. Following solution works for me.
This code is from the UserControl class:
protected void Page_Init( object sender, EventArgs e )
{
const string scriptKey = "UserControlScript";
if( !Page.ClientScript.IsClientScriptIncludeRegistered( Page.GetType(), scriptKey ) )
{
Page.ClientScript.RegisterClientScriptInclude( Page.GetType(), scriptKey, ResolveClientUrl("~/js/UserControl.js" ) );
}
}
I used Page_Init because I need to do some more initialization that has to be done before Page_Load of the nesting page is called.
It appears its not possible to use Page.ClientScript to add scripts to the header of the page.

Setting page title from # Page directive in ASP.NET using master pages

I am using master pages and am having trouble setting page titles from the # Page directive. All of my classes inherit from a class myPage which inherits from the ASP.NET System.Web.UI.Page class. Please Note: I have runat="server" set in my master page's head tag.
Here's what my # Page directives look like for the file test.aspx.vb:
<%# Page language="VB" MasterPageFile="~/MainMaster.master"
autoeventwireup="false" CodeFile="test.aspx.vb"
Inherits="test" Title="test" %>
Here's what test.aspx.vb looks like:
Partial Class test
Inherits myPage
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
This is what my master file, MainMaster.master, looks like:
<%# Master Language="VB" CodeFile="MainMaster.master.vb" Inherits="MainMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>untitled</title>
</head>
...
Now, when you go to view test.aspx in a browser you'd expect to see the title 'test'. but instead you will see 'untitled' as per the master page. Through trial and error, I modified the test class to inherit from System.Web.UI.Page directly, instead of myPage like this:
Partial Class test
Inherits Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
and everything worked just fine. Why would my pages being children of myPage instead of System.Web.UI.Page prevent the title from being set correctly in the # Page directive?
I realize that I could just set the page titles programmatically through the Page_Load methods in every page, but I'd rather do it in the # Page directives in the .aspx files.
This is a very weird and frustrating problem, and I'm at a loss!
Thanks!!!
I thank everyone for their help; I have found a solution. The problem was that the myPage class had a property for Title, but in the Set part of the property was not passing the changes on to Page.Title as it should have been.
A one line change fixed my problem :)
What methods do you have in your base page (myPage.vb).
If you are overriding any of the default methods, are you calling the base versions of those pages?
in C# I'd have something like this:
protected override void OnInit(EventArgs e)
{
// Do my custom processing.
// Don't forget to call base OnInit here:
base.OnInit(e);
}
If you don't call these methods, then the events that happen in them for you (like wiring up the masterpage's title) won't fire.
I have a very similar set up to you. I have content pages inheriting from a custom base page which is itself inheriting from page. I am not having any issues with the title being set on the aspx and being shown in the browser. The only difference I see between my code and yours is my master page has the autoeventwireup property where your master page does not, and also your master page has a property called codefile and mine has codebehind.
Content Page:
<%# Page Title="Login to Application X" Language="vb" AutoEventWireup="false" MasterPageFile="~/masterpages/mymasterpage.Master"
CodeBehind="login.aspx.vb" Inherits=".login" %>
Master Page:
<%# Master Language="VB" AutoEventWireup="false" CodeBehind="mymasterpage.master.vb"
Inherits=".mymasterpage" %>

GetCallbackEventReference doesn't work synchronously

I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous.
Now, the documentation says that the 5th parameter (see below) controls this. Specifically, when you pass 'false' it's supposed to be a non-asynchronous call. However, regardless if it's true or false, it still processes the call asynchronously.
Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);
Is there a work-around for this or perhaps I'm doing something wrong?
ASPX Page
<%# Page Language="VB" AutoEventWireup="false" CodeFile="How-to-use-GetCallbackEventReference.aspx.vb" Inherits="How_to_use_Callback" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to use GetCallbackEventReference</title>
<script type="text/javascript">
function GetNumber() {
UseCallback();
}
function GetRandomNumberFromServer(txtGetNumber, context) {
document.forms[0].txtGetNumber.value = txtGetNumber
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Get Random Number" onclick="GetNumber()" /><br /><br />
<asp:TextBox ID="txtGetNumber" runat="server"></asp:TextBox> </div>
</form>
</body>
</html>
Code Behind
Partial Class How_to_use_Callback
Inherits System.Web.UI.Page
Implements System.Web.UI.ICallbackEventHandler
Dim CallbackResult As String = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Me, "arg", "GetRandomNumberFromServer", "context")
Dim cbScript As String = "function UseCallback(arg,context)" & "{" & cbReference & " ; " & "}"
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "UseCallback", cbScript, True)
End Sub
Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
Return CallbackResult
End Function
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
CallbackResult = Rnd().ToString()
End Sub
End Class
For any other poor souls still using the MS AJAX library I found the following post:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/f4134c2e-ca04-423a-9da3-c613713a7b52/synchronous-callbacks-with-the-net-20-framework?forum=netfxjscript
The last comment from an MS source says:
This is actually by design. In order not to block the UI of the browser, this parameter doesn't actually do the request synchronously but makes sure the requests are queued and only one is going on at any given time. The effect is pretty much the same, except that the end-user can still use the browser UI while the request is going on and he won't have to kill the process if the server fails to respond or the network connection falls.
The MSDN page confirms this:
When sending data synchronously in a callback scenario, synchronous callbacks return immediately and do not block the browser. No two synchronous callbacks callback can execute at the same time in the browser. If a second synchronous callback is fired while one is currently pending, the second synchronous callback cancels the first and only the second callback will return.

Resources