I have a simple ASPX page that inherits from MasterPage:
(Popup.master)
<div class="text_container">
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
(Privacy.aspx)
Privacy
<asp:Content ID="BodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
I need to add a HTML content inside the Privacy.aspx.cs:
public partial class Privacy : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
ContentPlaceHolder body = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
I saw this example but as I see I need asp control inside.
How to add just HTML content to ContentPlaceHolder1?
A ContentPlaceHolder is intended to give you the ability to add controls in your page markup with a Content control and have them appear within the context of your master page. Given that, in Privacy.aspx you can add a generic html control in BodyContent Content Control and set the InnerContent property on the added control within your code behind.
Markup
<asp:Content ID="BodyContent" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">
<span id="SpanContent" runat="server"></span>
</asp:Content>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
SpanContent.InnerHtml = "<b>Hello!</b>";
}
Related
I have the following aspx page for eg: called choosemenu.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<div id="renderhere" runat="server">render user control here </div>
</form>
</body>
</html>
I have a list of ascx pages called
english.ascx
commerce.ascx
maths.ascx
I have to dynamically load the ascx files in my aspx page depending on the querystring in the aspx page.
I have the following contents in my aspx page in page_load event.
var control = (English)Page.LoadControl("/ascx/english.ascx");
How will I render the contents of the english.ascx page in the choosemenu.aspx that too in this tag
Also I have to pass some value in the ascx file. This is the static stuff.
<Menu:MNU ID="english" runat="server" HiLiter="<%#h %>"></Menu:MNU>
Loading a control from the server side
protected void Page_Load(object sender, EventArgs e)
{
Page.Controls.Add(Page.LoadControl("~/ascx/english.ascx")); //CHECK THE PATH
}
Loading a control from the server side and rendering it into a div
If you want to render it in a specific div you might write:
protected void Page_Load(object sender, EventArgs e)
{
UserControl uc = (UserControl)Page.LoadControl("~/ascx/english.ascx");
uc.MyParameter = 1;
uc.Id = 2;
uc.someMethodToInitialize();
div1.Controls.Add(uc);
}
and in your aspx page:
<div id="div1" runat="server">
</div>
Loading a control from the server side initializing the control with parameters
If your control has a constructor with parameters, you have to use:
public English_Control(int MyParameter, int Id)
{
//code here..
}
In you aspx.cs file you can initialize with:
UserControl uc = (UserControl)Page.LoadControl(typeof(English_Control), new object[] {1, 2});
div1.Controls.Add(uc);
In order for the control's postback values to be available, you must load and reload it no later than PreInit. Here is the code you need to do that.
protected override void OnPreInit(EventArgs e)
{
string controlToLoad = String.Empty;
//logic to determine which control to load
UserControl userControl = (UserControl)LoadControl(controlToLoad);
renderhere.Controls.Add(userControl);
base.OnPreInit(e);
}
As per MSDN:
Pre-Init event used to "Create or re-create dynamic controls."
Inside my ASP.NET application all my web content pages are derived from a base class which is derived from System.Web.UI.Page. Inside this base class I need to get some controls found in one derived class, SamplePage.aspx : BaseClass.cs. It I add the C# code below on Page Load inside SamplePage.aspx it finds the ContentPlaceHolderControl,
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder> /* defined in the master page */
/* inside SamplePage.aspx */
<ajaxtoolkit:tabcontainer runat="server" id="tabsmain" height="405px" Width="625px">
ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
AjaxControlToolkit.TabContainer container = (AjaxControlToolkit.TabContainer)cph.FindControl("tabsmain");
whereas if I add it inside the base class I get this error:
Content controls have to be top-level controls in a content page or a nested master page that references a master page.
Is there a way I can get the ContentPlaceHolder inside my base class too? And how can I access it?
Here is complete sample code how you can access ContentPlaceHolder:
First master code (Site1.master):
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebTesterInherit.Site1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Now custom class that inherits from Page:
public class MyPage: System.Web.UI.Page
{
public System.Web.UI.WebControls.ContentPlaceHolder GetMyContentPlaceHolder()
{
System.Web.UI.WebControls.ContentPlaceHolder holder = null;
Site1 site = this.Master as Site1;
if (site != null)
{
holder = site.FindControl("ContentPlaceHolder1") as System.Web.UI.WebControls.ContentPlaceHolder;
}
return holder;
}
}
And finally page that inherits from MyPage (Default.aspx):
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTesterInherit.Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click"/><br />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</asp:Content>
Code for Default.aspx:
public partial class Default : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
try
{
System.Web.UI.WebControls.ContentPlaceHolder holder = base.GetMyContentPlaceHolder();
lblMessage.Text = string.Format("Holder contains {0} control(s).", holder.Controls.Count);
}
catch (Exception ex)
{
lblMessage.Text = string.Format("Error: {0}", ex.Message);
}
}
}
I've checked and you can find a control nested in ContentPlaceHolder from base class OnLoad method.
Sure it can be done... but remember that some pages may have different controls in theirs CPH. Are you sure that you are in the context of a page which actually has tabsmain control?
I think if you have to do such things you have some design problem. A mix of master page and downward FindControl (base class -> derived class) just doesn't feel right.
Universal "search by id and type" method:
protected T GetControlOfType<T>(Control root, string id) where T : Control {
var stack = new Stack<Control>();
stack.Push(root);
while (stack.Count > 0) {
var control = stack.Pop();
var typedControl = control as T;
if (typedControl != null && string.Compare(id, typedControl.ID, StringComparison.Ordinal) == 0) {
return typedControl;
}
foreach (Control child in control.Controls) {
stack.Push(child);
}
}
return default(T);
}
Usage:
var control = GetControlOfType<MyControl>(Page, "MyControlServerID");
Based on my current understandings, when you have an UpdatePanel control there is no full postback. Therefore if I dynamically add custom user controls and they have UpdatePanels that are updated in their code they shouldnt disappear from the page they are loaded into, right? Apparently not. I made a simple project to test and still my dynamic controls disappear when clicked even though they should not be triggering a full postback. I have an aspx page that loads the controls:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TESTmultipleScriptManagerControls.aspx.cs" Inherits="myPlayground.TESTmultipleScriptManagerControls" %>
<!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 id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
With the following code behind:
protected void Button1_Click(object sender, EventArgs e)
{
TESTcontrol1 temp = LoadControl("TESTcontrol1.ascx") as TESTcontrol1;
PlaceHolder1.Controls.Add(temp);
TESTcontrol1 temp2 = LoadControl("TESTcontrol1.ascx") as TESTcontrol1;
PlaceHolder1.Controls.Add(temp2);
}
And a simple user control:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TESTcontrol1.ascx.cs" Inherits="myPlayground.TESTcontrol1" %>
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
</asp:ScriptManagerProxy>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
With the following code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = System.DateTime.Now.ToString();
}
Any ideas on why the controls are disappearing even though there shouldnt be a postback triggering?
OK based on my current understandings, when you have an UpdatePanel
control there is no full postback.
Postbacks triggered from UpdatePanels always execute the full page life-cycle. All the events are triggered normally. It makes no difference whether you use an UpdatePanel or not. Every time you add a control programmatically you need to re-add it on every postback.
Read this post, it may help you understand a bit better what's going on here.
By End of the Page Life Cycle all the controls generated at Runtime/Compile Time will be Disposed.
Below are the Page Events. Please set the BreakPoint on each Event and you can figure out that on each Asynchronous/Synchronous Request, all these Page Events are being executed.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
}
protected override void OnPreLoad(EventArgs e)
{
base.OnPreLoad(e);
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
protected override void OnUnload(EventArgs e)
{
base.OnUnload(e);
}
You need to populate them on each Page Init event in order to persist Viewstate, also events for controls added inside an update panel during button clicks do not seems to get registered until the next Postback. My suggestion is to keep a list of what you have added dynamically, and store it in a session variable
I have implemented master pages using this example How to implement a status bar in an ASP.NET application?. I have a property on my SiteMaster.cs inherited MasterPage called Environment. On my MasterPage.master I have this code:
<body>
<form id="frmMaster" runat="server">
<.. some content removed for brevity ...>
Environment: <%= this.Environment %>
</form>
</body>
What I would like to do is evaluate this.Environment and if it is "LIVE" then colour the background of this.Environment text red, and if it's "TEST" colour it yellow. How would I do this?
UPDATE I've just added this code to MasterPage.master
protected void Page_Load(object sender, EventArgs e)
{
lblEnvironment.Text = this.Environment;
if (this.Environment == "LIVE")
{
lblEnvironment.BackColor = System.Drawing.Color.Red;
}
}
The page loads, but the text does not get set, it's blank! Also the old text, that was populated is now blank too (I left the old code there for now). I also get a warning in Visual Studio:
'ASP.masterpage_master.Page_Load(object,
System.EventArgs)' hides inherited
member 'SiteMaster.Page_Load(object,
System.EventArgs)'. Use the new
keyword if hiding was intended.
UPDATE2: This is what I have in SiteMaster.cs
using System;
using System.Web.UI;
public class SiteMaster : MasterPage
{
public string StatusText { get; set; }
public string StatusTime { get; set; }
public string Environment { get; set; }
protected virtual void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (Session["status"] != null)
{
this.StatusText = Session["status"].ToString();
this.StatusTime = Session["statusTime"].ToString();
}
this.Environment = Session["environment"].ToString();
}
}
}
Instead of using the <%= syntax to print out the environment (this is using Response.Write), consider using a server control like a Literal or a Label. As you want to change the background colour, this suggests styling (CSS), so a Label would be appropriate.
(A Literal is just a text placeholder and renders no HTML, whereas a Label (usually) renders the text inside <span> tags.)
So I would change your master page markup to
Environment: <asp:Label ID="environmentLabel" runat="server" />
In the code-behind, set the Text property of environmentLabel to this.Environment. At the same time, test the value of the evironment, and set the BackColor property of the label as appropriate (or apply a CSS class).
UPDATE:
For a master page, you just need one class, which will inherit from System.Web.UI.MasterPage. If you create this in Visual Studio and call it SiteMaster, you'll get 3 files:
SiteMaster.Master (the markup)
SiteMaster.Master.cs (the code-behind)
SiteMaster.Master.designer.cs (automatically generated/updated)
In the SiteMaster.Master file, you'll want something like this:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="SiteMaster.master.cs" Inherits="WebApplication1.SiteMaster" %>
<!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>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="environmentLabel" runat="server" />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" />
</div>
</form>
</body>
</html>
In SiteMaster.Master.cs, you'll need something like this:
using System;
namespace WebApplication1
{
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
this.environmentLabel.Text = "environment";
this.environmentLabel.BackColor = System.Drawing.Color.Red;
}
}
}
As the environment label is on the master page, any normal page (ASPX) using this master page will get the label displayed. Every time a page is loaded, the Page_Load event in SiteMaster.Master.cs will be called, and the text will be updated. You don't need to define the MasterPage class yourself, that's provided by the .NET framework.
You may want to improve this Page_Load method, either by using ViewState and therefore only setting the text if you're not doing a PostBack, or by disabling ViewState on the environmentLabel control.
Finally, you'll have one or more ASPX pages in your site, with something like this at the top of the markup:
<%# Page Title="" Language="C#" MasterPageFile="~/SiteMaster.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
something like this..
var preTag = #" <font style=""background:yellow;color:#ff0000;font-weight:600;""><b>";
var postTag = " </b></font>";
Environment: <%= ((this.Environment=="LIVE") ? (preTag + this.Environment + postTag) : this.Environment) %>
You can also move the code from Page_Load to Page_PreRender in MasterPage.master and it should work.. it was blank because MasterPage.master Page_Load overwritten the Page_Load of SiteMaster.Master thus Environment was never assigned.
i"m using asp.net FileUpload , after user input file he click on save button
in the c# i have this function
protected void btnUploadImages_Click(object sender, EventArgs e)
{
SaveImages(FileUpload1, "", returnAlbumId, out returnPhotoId);
}
this function save the image from the FileUpload1 so far all work as it"s should
but after the postback when i push the refresh button on the page i"m go to this function again , SaveImages function save the same image again .
the FileUpload1 didn't clear after the postback
thanks
Even i got the Same Problem I have resolved like Below.
After uploading the File If you Redirect to same page or some other page in your project. After Redirection Response will not be there once you redirected.
In My ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm.aspx.cs" Inherits="WebApplication.WebForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
In My Code Behind
public partial class WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("~");
path = path + FileUpload1.FileName;
FileUpload1.SaveAs(path);
Response.Redirect("WebForm.aspx"); // Responce will be cleared. This Redirection will do the Trick
//Put the debugger and check it will work
}
}
Here, to show the success and error messages try to use sessions.