How to Access PagesSection Property in Code-behind of Asp.NET - asp.net

I'm in the code behind of a user control. I need to access one of the page's properties (EnableSessionState).
Originally, this would be defined something like this in aspx:
<%# Page Language="C#" EnableSessionState="ReadOnly" %>
However, I want to dynamically change this value in the code behind.
I looked at this answer:
PagesSection pages = WebConfigurationManager.OpenWebConfiguration("").GetSection("system.web/pages") as PagesSection;
pages.EnableSessionState = PagesEnableSessionState.ReadOnly;
Unfortunately, I'm just trying to read the header. Also considered this answer:
PagesSection pagesSection = new PagesSection();
pagesSection.EnableSessionState = PagesEnableSessionState.ReadOnly;
But I'm not trying to read default values, I'm trying to set the actual page's values.
Unfortunately, there is no property like this.Page.PagesSection, so is there another way of going about this?

Since the goal was to modify session state behaviour, according to this blog, it is possible to access using the following line:
Context.SetSessionStateBehavior(SessionStateBehavior.ReadOnly);

Related

Accessing the ControlsPlace Holders from Master Page

Hello I have been stuck with this situation for quite some time? Looking for some help here?
I have defined Nested Master Page (1 Default for WebApp and other Custom Master Page referencing the Default One)
The following is the code snipet from content page(say content.aspx) consuming my Custom Master Page
in aspx source code I have included:
%# MasterType VirtualPath="~/NestedMasterPage1.master" %>
and in code behind file ie. custom.aspx.cs (This is where the problem is):
ContentPlaceHolder masterContentPlaceHolder = (ContentPlaceHolder)Page.Master.Master.FindControl("MainContent"); //works well
ContentPlaceHolder nestedContentPlaceHolderHeading = (ContentPlaceHolder)masterContentPlaceHolder.FindControl("NestedMasterHeading"); //works well
Label NewsHeadLines = (Label)nestedContentPlaceHolderHeading.FindControl("lblSubSectionHeader"); //returns null?? The Control ID is all checked and is the same in the Nested Master Page.
**NewsHeadLines.Text = "Testing";** //System.NullReferenceException:
Object reference not set to an instance of an object.
Is it happening because I have nested my Control(here the label) in HTML Tables,rows and columns? Please advise? And I have double checked the control names or IDs.
I believe you might be missing one or two nested containers. Try this; instead of you trying to figure out the nested containers try having a common programming logic to get them. Have a look at Rick Strahl's blog post

How can I pass arguments on a ContentPlaceHolder?

Ok, so here is the setup. I have a master page. The page is assigned to a aspx file programatically in the PreInit function. This all works as expected.
I have a function that runs through all the controls on the page an looks for ContentPlaceHolder controls with specific IDs. When a specific ID is found the control is processed (specific content is placed there based on the ID and other information). This all works as expected.
I have a situation where I would like to pass information to my processor function from the control. I would like to be able to, based on an attribute, do different things. For example I would like to be able to put something like this on the masterpage:
<asp:ContentPlaceHolder id="CMS_EXTRABLOCK1" type="text" runat="server"></asp:ContentPlaceHolder>
Note that the type="text" attribute is not a standard attribute. I would like to be able to in the c# code do something like where ctrl is the ContentPlaceHolder.
if (ctrl.Attributes["type"] == "text") {} else {}
Now none of that will work as I get a parse error with the added attribute. So is there a way around the problem while still using the ContentPlaceHolder control? If at all possible I would like to continue using the ContentPlaceHolder control type for consistency with the rest of the code. If I can't use the ContentPlaceHolder in any manner then what would be an equally ideal asp control for this type of situation?

Databinding to a property?

I'm using the following syntax to bind to a div element:
<div id="previewdiv"><%=Preview%></div>
Where Preview is a property on my page.
The catch is that I'm creating this in Javascript on a new page in an onclick event. On the server side, I'm able to reference the new page via this property but for some reason when the page is postback the variable is getting set to the default initialized value and not to the value that I set in my page, i.e Preview = string. When I postback a second time then the page will be updated with the value I set.
I could perhaps move the code to the Init but I need to get values from controls to Initialize this property.
Ideas?
The problem you're running into is that, using traditional ASP.NET Web Forms, <%= %> code is evaluated very early in the page lifecycle, before your code has had a chance to run.
Instead, you want to use ASP.NET Data Binding, which uses a different syntax, like this: <%# %>. (note the "#"). Then, to get this code to render, you've got to call the DataBind() of some server-side control when you're ready to replace the template with your actual data.
So in your server code you do something like this:
Preview = someString;
previewDiv.DataBind();
And in your markup, something like this:
<div runat=server id="previewdiv"><%#Preview%></div>

Reuse a Variable Multiple Times on an ASP.NET Page

I feel somewhat foolish asking such a simple question, but I can't seem to find an answer. I'm new to ASP.NET (C#), but I'm learning by building a simple set of web pages that display a report. I have a variable that represents a company name. I need to output this variable in multiple places on the web page. The only way I have found to output a variable this is with:
company_name.Text = "Acme Windows";
then
<asp:literal id="company_name" runat="server" />
My problem is that I want to use company_name in multiple places on the page. Do I really have to create a separate variable holding the the same value for each time it is placed on the page? If I just copy the above XML code to all the places I want to show the variable it obviously creates a compile error since that ID is already defined.
I feel like I'm missing something very obvious.
The easiest way to do this is to create a string variable or property in your code-behind class and use the <%= %> notation (short for Response.Write) to render it on your page inline:
// You can do this anywhere on your .aspx, as many times as you like.
<%= this.CompanyName %>
// Better yet, html encode the value to protect against various threats,
// such as cross-site script injection (XSS)
<%= HttpUtility.HtmlEncode(this.CompanyName) %>
.NET 4.0 introduces a new shortcut notation (Html Encoding Blocks) to html-encode your output:
<%: this.CompanyName %>
Regarding your original approach, ASP.NET web controls like Literal represent individual parts of a web page - you can't use them multiple times on a page because the object instance company_name refers to the specific part of the HTML generated by the <asp:literal> in your .aspx page.
In this case, you create a property on the page and output that in every place you need it.
public string CompanyName { get { return "Acme Windows"; } }
And in the aspx:
.NET 4.0:
<%:this.CompanyName%>
Before 4.0:
<%=this.companyName%>
You could add the control dynamically:
Literal myLiteral = new Literal();
myLiteral.text = "Acme Windows";
this.Page.Controls.Add(myLiteral);
You can also add the control within a specific control on the page, by changing the this.Page.Controls reference to the particular control you want to add the literal to.
Why is this a community wiki?
Anyway, you have several possibilities to achieve what you want. Placing multiple variables holding the same name is for sure not best practice. If you have it filled with, let's call it, "semi-dynamic" value, I'd not put it hardcoded within your code. What I would do is to use a global resource file.
You create a new resource file in the App_GlobalResources folder and add a key "COMPANY_NAME" with value "Acme Windows". Then within your ASPX code you can do something like
<asp:literal id="company_name" runat="server" Text="<%$ Resources:GlobalResources, Button_Save %>"/>
I've written a blog post some time ago which details this approach. The advantage of the resource file is that you don't have to touch the code.
If you want to further "refactor" then - assuming you have some general company info you have to display on different positions on the page - you could create a separate UserControl which contains the information like company name, phone number, contact info etc. Within that control you have your literal, label, whatever you use to display that information exactly 1 time. This UserControl is then placed on the places on the actual page where you need it, even multiple times.
The simplest answer is you need to define multiple controls.
But a better solution would be to do this:
Create a property on the code behind side of things:
protected CompanyName{get;set;}
Then, in the aspx side of things, reference that with the <%= %> commands
<span><%=CompanyName %></span>

What's the difference in behavior between adding a control to an ASPX page directly, loading a control programmatically & adding to a placeholder?

Is there a difference in behavior between adding a control to the ASPX page directly and loading a control programmatically and adding to a placeholder?
The control inherits from System.Web.UI.WebControls.DataBoundControl.
The reason I ask is that I have a control that works when I add it to the ASPX page like so:
...
<blah:GoogleMap ID="GoogleMap1" runat="server" Width="640px" Height="600px" ... DataSourceID="_odsMarkers" DataAddressField="Address" DataTextField="Description">
</blah:GoogleMap>
...
But not when I use the following in a codebehind page:
GoogleMap map = (GoogleMap)this.LoadControl(typeof(GoogleMap), new object[] { });
//... set properties
this.placeholder1.Controls.Add(map); //add to placeholder
Anyone have any ideas why this might be the case?
The control tree ends up the same if you define in markup or add programmatically. However there is plenty of room for the control implementor to screw up along the way.
You can go look how ASP.NET compiles the aspx:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
The timing when the control is added to the page might be an issue. The usual pattern is add the control in an overload of the CreateChildControls method. If the control needs to resolve viewstate you need to make sure this is called during init, e.g. by calling EnsureChildControls.
Adding to ninja's debbugging hint. Does it make any difference if you add a label the same way. Does it show up?
Is this a user control or server control?
If it's a user control they should be loaded by their path and not their type:
GoogleMap map = (GoogleMap)this.LoadControl("~/Controls/GoogleMap.ascx");
If it's server control then you can just new up an instance:
GoogleMap map = new GoogleMap();
after you have the instance and add it to the control tree (by inserting it into the PlaceHolder) it should perform the same as when it would have been declared in the markup.
If you are setting properties outside of the LoadControl call, why are you making that new empty object array instead of just using the overload that has one parameter?
Also, if you attach a debugger to it and step through, do you notice anything weird about the control before you do your Controls.Add() call? Is there an exception being thrown? if so, which one? if not, what does the markup in the browser look like for where the placeholder is?
"Works" is kind of ambiguous, but if you mean, event handlers are never executed, you need to load it in the page onload event.
If the control requires the use of viewstate you must ensure that it is added to the page BEFORE the Page_Load event, otherwise viewstate will not be populated and most likely events and other items will not function properly.
One important difference is that if you create a control dynamically, you will not get, by default, any values from skins set. You must manually call control.ApplyStyleSheetSkin(page): http://msdn.microsoft.com/en-us/library/system.web.ui.control.applystylesheetskin.aspx

Resources