I'm using VisualStudio 2013 Express for WEB, and I created an empty web application, and then added a new web form.
I'm trying to learn ASP.NET, and I learned that in the session / page life cycle there is Page_Load where I can execute thing that will happen just after the page loads. The thing is I learned that it is possible to put the Page_Load event under <script> before the <HTML> tag.
(The aspx file name is Register) When I try this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="Learning.Register" %>
<!DOCTYPE html>
<script runat="server">
int randomnumber = 0;
public void Page_Load()
{
Random rnd = new Random();
randomnumber = rnd.Next(100000, 1000000);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<% Response.Write(randomnumber); %>
</div>
</form>
</body>
</html>
All I get is 0 for some reason.
Also, I noticed that under Register.aspx.cs I have this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Learning
{
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
You can definitely put the server side code in aspx using script tag. But the page load syntax should exactly match as it is in your code behind(.cs file)
Page_Load(object sender, EventArgs e)
In your script code you have just Page_Load() which does not trigger at all.
If you need this to be excecuted then you need to remove the function in the code behind and replace the method signature in the script tag
in the script tag you need to have base.OnLoad(e)
protected void Page_Load(object sender, EventArgs e)
{
base.OnLoad(e)
Random rnd = new Random();
randomnumber = rnd.Next(100000, 1000000);
}
That's because you are overriding the behavior of the base class, and if you don't call base.OnLoad(e) then Page_Load would not run in the markup side.
Related
I have an ASP.net WebForm. The markup is like:
<div>
<input type="text" id="input" runat="server" value=" " />
<asp:Button Text="send" OnClick="btnsend_Click" ID="btnsend" runat="server" />
</div>
This HTML is generated at runtime . The events are defined in the code behind file.
I need to add these controls at runtime. I tried to use the Literal-Control but the controls are working just like HTML Controls and not like ASP.net Controls.
EDIT:
Note: The Project type should be Website, not a web Application. Web application won't support on demand compilation where website yes, it is.
If I understood currectly, you want to take the Markup from User which contains even asp.net controls and scriplets too.
if this is the case, Follow below steps:
Create a dummy .ascx control file, like DynamicMarkup.ascx with empty content
Add this user control to the page (xxxx.aspx) where you want to show this control statically so it registered to the page
<%# Register src="~/DynamicMarkup.ascx"
tagname="DynamicMarkup" tagprefix="MyASP" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder runat="server"
ID="DynamicMarkupContainer" ></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Write user input markup (may be get from database based on your criteria) to the DynamicMarkup.ascx file in page OnInit of the page (xxxx.aspx) And the create object of this DynamicMarkup
DynamicMarkup dynamicMarkup = LoadControl("~/DynamicMarkup.ascx") as
DynamicMarkup;
DynamicMarkupContainer.Controls.Add(ucSimpleControl);
I have not tested this approach, Just give a thought, With this you may get some session overwriting issue which you need handle.
Hope this will help!!
OLD:
is this the one that you are expecting? TextBox, and Button controls are available in System.Web.UI.WebControls namespace.
void Page_Load(Object sender, EventArgs e)
{
TextBox input = new TextBox();
input.Id ="input";
this.PlaceHolder.Controls.Add(input);
Button btnSend=new Button();
btnSend.Id ="btnSend";
btnSend.Text="Send";
btnSend.Click += new EventHandler(btnSend_Click);
this.PlaceHolder.Controls.Add(btnSend);
}
void btnSend_Click(object sender, EventArgs e)
{
// throw new NotImplementedException();
}
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder ID="phHolder" runat="server"></asp:PlaceHolder>
</form>
</body>
</html>
code behind :
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Init()
{
GenerateContorls();
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void GenerateContorls()
{
TextBox newTxt = new TextBox() { ID = "txtsend" };
Button newBtn = new Button() { Text = "Send", ID = "btnsend" };
newBtn.Click += btnsend_Click;
phHolder.Controls.Add(newTxt);
phHolder.Controls.Add(newBtn);
}
protected void btnsend_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)this.FindControl("txtsend");
//your code
}
}
hope it helps
I've created a very simple bit of code in C# to display data in an asp:Table. On the initial page load all looks great. I've used an AJAX timer to refresh every 15 seconds to keep the data up to date. The problem is after it refreshes the table shows all the data duplicated. I've tried debugging and again all looks good until the AJAX refresh and then it seems to jump all over the place in the C# code rather than following the expected sequence.
Hopefully I've not approached this in completely the wrong way but if I have please tell me! Is there a way to prevent/fix this duplication?
I've replicated the problem code here in a very simple form. Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="testASPTables._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Table ID="Table1" runat="server">
</asp:Table>
<asp:Timer ID="Timer1" runat="server" Interval="15000" OnTick="Timer1_Tick">
</asp:Timer>
</div>
</form>
</body>
</html>
...and the codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace testASPTables
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TableRow[] tRows = new TableRow[5];
TableCell[] tCells = new TableCell[5];
for (int i = 0; i < 5; i++)
{
tRows[i] = new TableRow();
Table1.Rows.Add(tRows[i]);
tCells[i] = new TableCell();
tRows[i].Cells.Add(tCells[i]);
tCells[i].Text = "Cell Number: " + i.ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Page_Load(sender, e);
}
}
}
You're calling Page_Load twice. Page_Load runs on postback, then you call it again from Timer1_Click.
You need to always be concious of whether the page is in a postback or not and how Page_Load works.
Here's what I'd do.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LoadTableData();
}
}
protected void LoadTableData()
{
Table1.Rows.Clear(); //I added this
TableRow[] tRows = new TableRow[5];
TableCell[] tCells = new TableCell[5];
for (int i = 0; i < 5; i++)
{
tRows[i] = new TableRow();
Table1.Rows.Add(tRows[i]);
tCells[i] = new TableCell();
tRows[i].Cells.Add(tCells[i]);
tCells[i].Text = "Cell Number: " + i.ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
LoadTableData();
}
Oh, and in addition to that, you'd need to clear the existing table rows.
By the way, this is very inefficient. You're reloading the entire table every 15 seconds. Multiple that by a few clients and you're practically performing a DoS attack on yourself. Consider using SignalR to push new changes to the clients as rows are added to the underlying data.
I have a simple ASP.NET page with a button and a textbox, I want to click the button and have "Hello" appear in the textbox.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SOM.aspx.cs" Inherits="SOM" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div><br />
</div>
<asp:Button ID="MyBtn" runat="server" Text="Click" OnClick="SearchBtn_Click" />
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server" Width="268px"></asp:TextBox>
in the code behind I am able to use Intellisence to autocomplete TextBox1.Text = "Hello";
but then when I try to debug, the project fails to build saying
The name TextBox1 does not exist in the current context
Is there a property that I need to set?
///Code behind
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Input;
public partial class SOM: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SearchBtn_Click(object sender, EventArgs e)
{
//TextBox1.Text = "HI";
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
}
If any of the great answers here do not work, here's another solution that once caused me a few gray hairs, especially if you're using VS 2012.
If your project is a web application, delete the designer.cs file. Then right click on the aspx file and select "Convert to Web Application".
For as great as Visual Studio is, sometimes these stupid WTF things drive me absolutely nuts.
Your aspx page is not referencing the correct code behind.
In the head of your aspx page replace with
<%# Page Language="C#" AutoEventWireup="true" CodeFile="myName.aspx.cs" Inherits="myName" %>
That should work
NOTE: I now know this isn't the problem, I but updated my answer in case it solves someone else's problem.
If you are using a namespace somewhere between your codebehind or the aspx page, you have to make it consistent.
I will use "MyProject" as a sample namespace.
namespace MyProject
{
public partial class SOM: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SearchBtn_Click(object sender, EventArgs e)
{
TextBox1.Text = "HI";
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
In your aspx page, change Inherits="SOM" to Inherits="MyProject.SOM".
I need a value from javascript before the main page load and then want to use that value in code. The code which I am using for that purpose is:
I have make a test.aspx page. The code for which is as following:-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="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">
<title>Untitled Page</title> <script type="text/javascript" language="javascript">
function GetScreenHeightAndWidth()
{
var width = screen.width;
var height = screen.height;
var object = 'Label1';
document.getElementById(object ).innerHTML=height ;
//alert(height);
'<%Session["Screensize"] = "' + height +'"; %>' ;
}
</script>
</head>
<body onload="GetScreenHeightAndWidth();" >
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="test"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
The code for test.aspx.cs page is as following:-
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.IO;
using System.Windows.Forms;
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["Screensize"] = Label1.Text;
TextBox1.Text=Session["Screensize"].ToString();
}
}
The result is as following:-
768 test
while result what I need is 768 and 768.
Is there any way to solve the problem?
What you are asking is impossible to do. Why do you need to know the screen size on the server -side in the first place? Whatever you need to accommodate on the html produced by the server can be either adjusted via proper CSS rules or Javascript (JQuery if you prefer that framework)
If you set the width/height values to a hidden field from script, you can than access them from codebehind after a postback. Labels are not posted with the form so you cant use that.
First of all thanks to all of you for responding to my question. After much search I have found what I was exactly wanting. For this I have to use one more page and add this code in my original code:
if (!IsPostBack)
{
if (Session["ScreenResolution"] == null)
{
Response.Redirect("detectscreen.aspx");
}
else
{
Session["Screensize"] = Session["ScreenResolution"].ToString();
}
TextBox1.Text = Session["Screensize"].ToString();
}
And the code for new page is:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["action"] != null) {
Session["ScreenResolution"] = Request.QueryString["res"].ToString();
Response.Redirect("Catalogue.aspx");
}
}
and the script in the new page will be like this:
<script language="javascript" type="text/javascript">
res = "&res="+screen.height
top.location.href="detectscreen.aspx?action=set"+res
</script>
I have a web page with an empty div, id="PreAcquisitionDiv" runat="server"
In the C# code-behind, on Page_Load, I build up a table and set it to PreAcquisitionDiv.InnerHtml
My page displays OK. I cause a PostBack, intending to change the data in the table. In the code, the PreAcquisitionDiv.InnerHtml does change, but the table I put there the first time is still displayed on the page instead.
I have seen some warnings about using InnerHtml at all, but the examples of alternatives that I have seen are JavaScript.
I am using IE 8, but I observe the same behavior in Chrome.
Thank you for any suggestions!
For example, this code displays "SomeStuff" when it first displays the page; then still "SomeStuff" after the PostBack even though the InnerHtml was changed.
protected void Page_Load( object sender, EventArgs e )
{
StringBuilder html = new StringBuilder( #"<TABLE BORDER='1' WIDTH='100%'>" );
if( !IsPostBack )
{
html.Append(#"<TR><TD>SomeStuff</TD></TR>" );
}
else
{
html.Append( #"<TR><TD>Some New Stuff</TD></TR>" );
}
html.Append( #"</TABLE>" );
this.PreAcquisitionDiv.InnerHtml = html.ToString( );
}
If you are changing the HTML on post back are you running your function to set it on post back as well?
UPDATE: I copied and pasted your code and it works fine for me. Here is my entire code behind:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
namespace Sandbox
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder html = new StringBuilder(#"<TABLE BORDER='1' WIDTH='100%'>");
if (!IsPostBack)
{
html.Append(#"<TR><TD>SomeStuff</TD></TR>");
}
else
{
html.Append(#"<TR><TD>Some New Stuff</TD></TR>");
}
html.Append(#"</TABLE>");
this.PreAcquisitionDiv.InnerHtml = html.ToString();
}
protected void btnTest_OnClick(object sender, EventArgs e)
{
}
}
}
And here is my entire ASPX page
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Sandbox._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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div id="PreAcquisitionDiv" runat="server">
</div>
<asp:Button ID="btnTest" runat="server" OnClick="btnTest_OnClick" />
</form>
</body>
</html>