How can I pass arguments on a ContentPlaceHolder? - asp.net

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?

Related

What is the best way of setting the src of an iframe from a codebehind file in ASP.NET?

I have an iframe that has a dynamic URL based on the results of web API call. What is the best way of setting its src in the aspx page? Here is an example of the iframe:
<iframe id="dynamicframe" runat="server"></iframe>
Should I set it directly in the codebehind like so:
dynamicframe.Attributes["src"] = "http://dynamicurl.com";
Or should I create a property in the codebehind and reference it in the iframe:
<iframe id="dynamicframe" src="<%= dynamicFrameUrl %>"></iframe>
Or some other method altogether?
This is a general question that can stands the same for any html tag.
The alternative third option is to use a literal control and fully render the iframe on code behind as:
txtLiteral.Text = "string.Format(
"<iframe id=\"dynamicfrmae\" src=\"{0}\"></iframe>", PageUrlForSrc );
The different for all methods :
Direct write on page <%= %>
Not work with update panel
Its run the moment the page send to the browser (and not before on the page steps)
Not accessible as control
This is the method that I avoid most. I use it only when I like to left some calculations for later and avoid page cycle, or when I have responce.flush() just before it.
Write it using to literal
Compatible with UpdatePanel
Not accessible as control
Write it as attribute on code behind
Make the control pass the steps of the html cycle
Is accessible else where on the page as variable
The id of this control may change but you can avoid conflicts
All methods have their purpose, and I used then according what they fit best.
Well if you have the URL available to you in the code-behind file I would say option one is the most straight forward. However, I'm a little confused about the question, are you looking for a best-practice?

Asp.net yellow code <% vs Explicit asp control

I have a literal in my aspx called xxx.
Now lets go into the JS world.
I always used :
alert('audit.aspx?claim_id=<%= xxx.Text%>');
But Ive seen a code like this :
alert('audit.aspx?claim_id=<asp:Literal id="xxx" runat="server" />');
This is also working.
Can I conclude that the <asp:Literal is equal to <%= syntax ?
I know that he is a RUNAT server Item...
but again - I want to see the differences.
The asp:Literal control simply outputs the value of its Text property when the page is rendered. That's why the resulting JavaScript looks the same when viewed by the client. But the two are not the same, no.
<%= xxx.Text %> explicitly reads the value of this text property and writes it out. The Literal control will be elsewhere on the page, where its Text property will also be written out.
Placing the asp:Literal control within your JavaScript relies on the rendering of this control to place the value there, and because this is its location within your page, there's no need to have the same content rendered elsewhere.
However, neither taken in isolation seems an appropriate use of this control to my mind. If you have simple text you want written out, then expose it as a property of your Page-derived code-behind class.
The Literal class is basically a placeholder for text, but it also exposes events which you can hook into for greater control.
Have a look at the API here http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.literal.aspx

Referencing ids unknown at compile time

I'm making a user control to gather all the functionality for popups on my website in one place. When someone instantiates the control, they'll pass in a PopupID attribute, which is assigned to the id of a div inside the control, and will be used to call show() and hide() functions in javascript. I'm going to use content templates so that different stuff can be put inside the control by different kinds of popups.
The html for the popup will look something like this:
<div id="<%=PopupID %>" class="popup box" runat="server">
<asp:PlaceHolder runat="server" ID="popupPlaceHolder"></asp:PlaceHolder>
</div>
However, there is a problem: asp.net has the habit of giving controls different IDs when served up to the client than what you write in the html. So the ID of that div might not be <%=PopupID%> It could be somethling like #ctl00_whatever_<%=PopupID%>. Usually I get around this by putting something like:
<script type="text/javascript">
var ddlCountry0 = '<%=ddlCountry0.ClientID%>';
var ddlActivity0 = '<%=ddlActivity0.ClientID%>';
var chkPrivateContacts = '<%=chkPrivateContacts.ClientID%>';;
</script>
In the header for the page. Then when refering to things in the javascript you just do $(ddlCountry0) instead of $('ddlCountry0'). However, I don't see how I can do that in this case, As I don't know the ID of the element until someone instantiates it. What do I do to get around this?
Does the user control have CreateChildControls and OnPreRender methods you can override?
If a control is added and ID set correctly during CreateChildControls...the ClientID property is populated during OnPreRender, at which point the control itself could inject the necessary script block into the body or page header. People often use jQuery to help with this situation:
headerScript.AddLine("var ddlCountry0 = $('[ID$=" & Control.ClientID & "]').attr('id');")
Is that along the right lines?
In the end, I used ClientIDMode=Static to get around these problems.

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>

Resources