Something strange with ASP.Net Webforms - asp.net

I tried something by mistake and i do not understand why this is working:
I've created 2 asp.net web forms called page1.aspx and page2.aspx
On page1.aspx:
In code behind i declare a static string: field1.
I put a simple button.
When I click on this button:
field1="Hello world"
Response.Redirect("page2.aspx")
On page2.aspx, in Page_load, i display page1.field1 value.
When page2.aspx is loaded, page1.aspx should not be loaded in memory. I do not understand why page1.field1 still contains "Hello world value !"
Can anyone explain me why this code works ? Is it a good thing to work this way ?
Does asp store static fields in viewstate or session ?
Thanks
Here is page1.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="page1.aspx.cs" Inherits="WebApplication7.page1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Here is page1.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication7
{
public partial class page1 : System.Web.UI.Page
{
public static string field1;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
field1 = "Hello world";
Response.Redirect("page2.aspx");
}
}
}
Here is page2.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication7
{
public partial class page2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(page1.field1);
}
}
}

The keyword "static" means that only one instance of a given variable exists for a class. Static variables are used to define constants because their values can be retrieved by invoking the class without creating an instance of it.
Static variables can be initialized outside the member function or class definition.
Note
Unlike other member variables, only one copy of the static variable exists in memory for all the objects of that class. Therefore, all objects share one copy of the static variable in memory.
In your situation, you had set field1 = "Hello World" in Page1 and on button click you will be redirected on Page2 and write that field1 variable on your page which is the static variable of your Page1 class.

Once you make a field static, it will be in memory till app pool is recycled(full application memory is recycled). I don't know what you are trying, but declaring a static field in a code behind pages is not a good idea.

Related

asp.net OnPreLoad doesn't fire?

I can't figure out why my OnPreLoad function doesn't get fired for search.aspx.cs.
*Update * - OK, I figured out what's causing the problem, but I don't understand why it is a problem. I updated my question.
Here are three relevant files:
// search.aspx -- THIS <select runat="server"> CAUSED ALL the problem
<select runat="server" id="slctCategories">
<asp:Repeater runat="server" ID="optCategories">
<ItemTemplate>
<option value=""></option>
</ItemTemplate>
</asp:Repeater>
</select>
// search.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class search : BTPage
{
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
// BTPage.aspx.cs - the file that search.aspx.cs inherits from
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class BTPage : System.Web.UI.Page
{
protected SqlConnection cnx;
protected override void OnPreLoad(EventArgs e)
{
cnx = new SqlConnection(ConfigurationManager.AppSettings["database"]);
cnx.Open();
}
protected override void OnUnload(EventArgs e)
{
cnx.Close();
}
}
What's weird is that the OnUnload DOES get fired. What's going on? Why won't my OnPreLoad fire?
** UPDATE ** - I got my onpreload to fire after I changed <select runat="server"> to <select> in my search.aspx. Someone explain to me why this fixed the problem? I was struggling for hours with this.
There might be something strange with how you are using your select:
<select runat="server" id="slctCategories">
<asp:Repeater runat="server" ID="optCategories">
<ItemTemplate>
<option value=""></option>
</ItemTemplate>
</asp:Repeater>
</select>
You should not be nesting a Repeater inside that tag. I'm actually surprised you don't get a compilation/runtime error due to that.
You note that you found the DropDownList control to use instead. However, the HttpSelectList control also has a similar interface for adding items to it - you don't need an extra list control inside it.
My guess is, since removing that as a server control fixed the problem (which fixes the syntax weirdness), that there is something subtle going on which prevents the normal OnPreLoad from being fired in that syntax.
In BTPage you don't call base.OnPreLoad:
protected override void OnPreLoad(EventArgs e)
{
cnx = new SqlConnection(ConfigurationManager.AppSettings["database"]);
cnx.Open();
}
I don't know why this would prevent the search class overriding the method, though, or what the select has to do with anything. (e.g. it should have worked anyway). But it is generally good practice to call the base method in any overridden method (even ones like this that are there specifically for you to override). You don't know if anything else that is supposed to take place happens in the core Page.OnPreLoad method.

Access drop down list from code behind

I have an .aspx file that has 3 drop down lists:
ddlMake
ddlModel
ddlColour
i have a Page_Load function but i cant acces them in the Page_Load function...
using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace NorthwindCascading
{
public partial class _IndexBasic : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CarService service = new CarService();
List<string> Makes = service.GetCarMakes();
ddlMake.DataSource = Makes;
ddlMake.DataBind();
ddlMake.Items.Insert(0, " -- Select Make -- ");
}
}
}
}
I have added the code-behind file manually so i guess i am missing something... it just says that the ddlMake element is not defined in current context...any suggestions?
Rather than figure out what went wrong. I suggest you just simply delete the file and re-do what you have done again. Will save your time....
Make sure your CodeFile/CodeBehind attribute in the page directive is pointing to the correct file. If so, make sure the Inherits attribute in the page directive is naming the correct class name.
If you added the code behind manually, then the _IndexBasic.designer.cs probably doesn't contain the protected members, which would be why you cannot see them here. Or, your aspx is not referencing this as your codebehind.
Right-click on your .aspx page and hit Convert to Web Application - that will create and populate the designer file.

Accessing MasterPage object from an .aspx code-behind

I know we've done this before in another .aspx page that's using this master page. So I tried this in a new .aspx but for some reason, it is not recognizing the Master object. And the .aspx definitely is set to the master page in the page directive correctly and there's no errors to that effect:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
public partial class LandingPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Master.HideNavbar();
}
}
Try to reference your masterpage at your aspx file :
<%# MasterType virtualpath="~/YourMasterPage.master" %>
to get typed Master page class in your code you need to define what type is it, either in Page directive or with MasterType directive on page:
<%# Page masterPageFile="~/MasterPage.master"%>
<%# MasterType virtualPath="~/MasterPage.master"%>
If you don't have these directives, you can always cast Master property in code:
(MasterPage)this.Master
see also here
http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx
Edit:
is HideNavbar() method public?

How can I copy the DynamicData templates from another site?

I'm attempting to start using DynamicData functionality in a previously existing website. Basically I'm following this tutorial. When I got to the part about creating the Field Templates I decided I could probably create a new site with the Dynamic Data stuff built in, and then just copy the folder over.
Unfortunately when I do that and try to compile I get the error "Could not load type..." for just about every .ascx file in the DynamicData directory. I named the "new" project the same as the pre-existing site so that the namespace would be the same... but I can't think of what else I could be missing.
Everything looks ok, except that the *.ascx.Designer.cs files are showing inside the Solution Explorer. I tried deleting one and then copying that file back into just the directory but it didn't work. I'm assuming I need to do something special with those so that Visual studio handles them properly and can compile?
Here is one of the .aspx files:
<%# Control Language="C#" CodeBehind="FilterUserControl.ascx.cs" Inherits="EService.FilterUserControl" %>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
EnableViewState="true" ontextchanged="new">
<asp:ListItem Text="All" Value="" />
</asp:DropDownList>
Here is the matching .cs file:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.DynamicData;
namespace EService
{
public partial class FilterUserControl : System.Web.DynamicData.FilterUserControlBase
{
public event EventHandler SelectedIndexChanged
{
add
{
DropDownList1.SelectedIndexChanged += value;
}
remove
{
DropDownList1.SelectedIndexChanged -= value;
}
}
public override string SelectedValue
{
get
{
return DropDownList1.SelectedValue;
}
}
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateListControl(DropDownList1);
// Set the initial value if there is one
if (!String.IsNullOrEmpty(InitialValue))
DropDownList1.SelectedValue = InitialValue;
}
}
}
}
And here is the .ascx.designer.cs file:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1433
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EService
{
public partial class FilterUserControl
{
protected System.Web.UI.WebControls.DropDownList DropDownList1;
}
}
EDIT: If I create the file in the website, then copy the contents from the temporary site I created it seems to compile just fine. Really have no idea what the issue is here... I tried manually modifying files to match the results of copying and they still wouldn't work unless I actually created them in the site. It's just bizarre...
The problem was due to the temporary site creating the <%# Control > definitions with the CodeBehind property instead of the CodeFile property. For some reason pages in the actual website will only compile when CodeFile is declared...
DD will work with Either Website or Web Application. however when copying in from an other project the types need to be the same otherwise it's lot of editing to convert swee my article here Getting Dynamic Data Futures filters working in a File Based Website.

ASP.NET :Show background process status to User

I have a web page where it will input an excel/CSV file from the user and read the data from it and import to DB.While inserting each record.I just want to show the details about the record being inserted to the user.(Ex : Client Details of A is adding...)
Try this... Set the output to unbuffered (Response.BufferOutput), and include some javascript in your page that updates the UI as you see appropriate. For example, it might update a SPAN with a percentage complete or the details of the record you are processing. Then in your server code, output <script> tags that call the Javascript function from the Render override. Make sure you call Flush() at the appropriate times, and also Flush the base code after it Renders... The JS function calls should get sent down at the appropriate times and executed on the client, resulting in an updating page.
For example... Your HTML page might look like this:
<%# 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">
<title></title>
<script type="text/javascript">
function UpdateScreen(t) {
document.getElementById('output').innerHTML = t;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id='output'></div>
</div>
</form>
</body>
</html>
<script type="text/javascript">
UpdateScreen('hello');
</script>
and your codebehind will look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
Response.BufferOutput = false;
base.Render(writer);
Response.Flush();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Response.Write(string.Format("<script type='text/javascript'>UpdateScreen('{0}');</script>", i * 10));
Response.Flush();
}
}
}
}
I know this is an old question, and the owner of it may have moved on a long time ago. Anyway:
The proposed solution will not work on ASP.NET MVC. And if you ask me, which you don't, I'll say this is not the cleanest solution to the problem:
Here's a jQuery one,
And here's an IFrame one.

Resources