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."
Related
In code behind I have property called ReportFeatures and Page_Load event:
public partial class FeatureList : System.Web.UI.Page
{
protected string ReportFeatures;
protected void Page_Load(object sender, EventArgs e)
{
IEnumerable<ReportFeature> featureProps = fim.getFeatureProperties();
ReportFeatures = featureProps.ToJson();
}
}
In designer I tried to access ReportFeatures variable:
<head runat="server">
<title></title>
<script type="text/javascript">
window.reportFeatures = <%= ReportFeatures%>;
</script>
</head>
When page loaded I get this error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Any idea why I get that error, and how to fix it?
Instead of using <%= ... %> block, try using data binding expression syntax (<%# ... %>), because <%= ... %> implicitly calls Response.Write() method in Page.Header which counts as code block while data binding expression doesn't count:
<head runat="server">
<title></title>
<script type="text/javascript">
window.reportFeatures = <%# ReportFeatures %>;
</script>
</head>
Then add Page.Header.DataBind() method in Page_Load event, because you want to bind ReportFeatures inside <head> tag which contains runat="server" attribute:
protected void Page_Load(object sender, EventArgs e)
{
IEnumerable<ReportFeature> featureProps = fim.getFeatureProperties();
ReportFeatures = featureProps.ToJson();
// add this line
Page.Header.DataBind();
}
More details about this issue can be found here.
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>";
}
I am trying to add a few additional lines of code to the Page_Load method of an ASP.Net page, where the existing Page_Load code is stored in a compiled codebehind DLL. I don't have access to the source for the DLL, although I can extract the code for the Page_Load method using Dis#.
What is the best way to add the new code? I need the existing Page_Load code to execute, together with the new code, and it doesn't matter in what order they execute.
Specifically, I'm fixing an old application that uses the Telerik RadEditor which doesn't work correctly under Firefox 6. See this page for the exact code I'm adding.
If you can access the ASPX portion, you can try adding a code block to the ASPX, and overriding OnInit or OnPreInit, which should work fine for the code you're trying to add.
<script runat="server">
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Request.Browser.Browser.ToLowerInvariant() == "firefox")
{
System.Reflection.FieldInfo browserCheckedField = typeof(RadEditor).GetField("_browserCapabilitiesRetrieved", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
browserCheckedField.SetValue(RadEditor1, true);
System.Reflection.FieldInfo browserSupportedField = typeof(RadEditor).GetField("_isSupportedBrowser", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
browserSupportedField.SetValue(RadEditor1, true);
}
}
</script>
You can derive from the other Page class and add a Page.Load event handler:
public class YourPage : TheirPage
{
public YourPage() { Load += YourPage_Load; }
void YourPage_Load(object s, EventArgs e) { ... }
}
or even override OnLoad():
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
...
}
You would need to extract all source, add your code and rebuild the entire dll. There is not a way to do this without rebuilding the original assembly. This will be a problem if the original assembly is strong-named. Otherwise, it's a pain but you should be ok.
can you possibly hook into PreLoad in the aspx page? Controls are loaded at this point and you should be able to do what you need. Sometimes additional processing is required and you can hook into LoadComplete as well which I think may serve you best?
http://msdn.microsoft.com/en-us/library/system.web.ui.page.preload.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.page.onloadcomplete.aspx
If you can extract the code from the DLL by dissasembling it, you can disassociate the code behind the page and reimplement the logic in the markup.
<%# Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
lblTest.Text = "Something here";
}
</script>
<!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:Label ID="lblTest" runat="server" ></asp:Label>
</div>
</form>
</body>
</html>
You can derive from the existing class and override any of the rendering methods, such as the OnPreRender() method:
public class Class1 : _Default
{
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
// add your code here
}
}
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.