ASP.Net Placeholder vs if directive - asp.net

When working with markup if I want to include some content conditionally, I use a placeholder in a normal way:
<asp:Placeholder Visible=<%# IsExpired %>
<span>Prolong your subscription</span>
</asp:PlaceHolder>
Also I can use if-directive:
<% if(IsExpired) {%>
<span>Prolong your subscription</span>
<% }%>
I prefer using the first one just because it does not make my markup messy. And what's the best way to conditionally include content? From the performance point of view, are they similar?

native HTML tags are always faster than rendering server controls as there is no time spent for rendering them

I think there is hardly anything to do with performance whether way you choose here. But actually you may use the following code:
<asp:Label runat="server" Visible=<%# IsExpired %>
Prolong your subscription</asp:Label>
instead the other two. This could make it look more straight-forward.

I'd never use C# code in Web Forms view. In addition I will avoid setting the Visible property in the markup and I will set it in the code behind on some event.
phWhatever.Visible = IsExpired;
Quite often you can avoid creating the IsExpired property.
Of course what #Johnny suggested is correct. If you need to hide what is effectively only one control you hide the control directly.

Related

The Controls collection cannot be modified because the control contains code blocks - Error only when it is in head block

Agree my question is duplicate of this one and accepted answer works for me too. Let me clarify why.
When I have <%= in head it gives error.
When I have <%= in body it works.
When I have <%# in head it works.
I am just curious to know the reason for all three scenarios.
Additionally I created test project to emulate the issue but in that case all three situation works.
My page is too big and I am unable to decide what code to paste.
<%= %> is in fact doing Response.Write, which is literally writing symbols to the response. To the final markup that is.
Now notice that your head tag has this attribute runat="server". That makes it a server control. That is, this is not a final markup, and but rather a control that will output some markup to response during the control rendering stage. You cannot call Response.Write on this control, because it is not a final markup yet.
For the same reason it would work/not work in the body of the page. If you put it somewhere in plain markup it would work no problem:
<div><%= "Blah" %></div> <%-- works! --%>
But as soon as it appears inside anything with runat="server" you'll get an error
<div runat="server><%= "Blah" %></div> <%-- error! --%>
<asp:Panel runat="server"><%= "Blah" %></asp:Panel> <%-- error! --%>
Now <%# %> is a different beast. This is a data binding markup, something that is being evaluated when the server side control is being data bound. Thus is makes no sense (and is invalid) inside plain markup, and can be used whenever your control is bound to some data. Using it with header is not very common, use cases with GridView or Repeater are the most typical ones that come to mind.

Asp.net Variable is not working on the page

I have the following code:
<tr id="test" runat="server">
<td align="<%=myalignment%>">
I set myalignment = "center", however, when the page is rendered, it doesn't grab the variable. It just shows exactly how it is above. I wanted to programatically change certain TDs to "center" or "left" and I thought this would work. Any ideas?
If tr doesn't have runat="server", then it works fine...
Controls that run server-side can't have properties set declaratively and resolved dynamically via the <%= %> (Response.Write) syntax.
Expressions can be used, or in a pinch, you can use <%# %> databinding syntax, but then you need to call DataBind() on the control or page, and that can have nasty side effects.
As an alternative, you should be able to iterate over cells or reference specific cells in the codefile. You might have to add the runat=server attribute to each cell as well -- not sure about that.

<script> tags inside an <asp:repeater>

I'm outputting a few lines of Javascript within a Repeater control on an ASPX page. I want to use a value from my DataSource inside the script tag.
A very basic example might be:
<asp:Repeater ID="RepeaterBlah" runat="server">
<ItemTemplate>
Hello <%# DataBinder.Eval(Container.DataItem, "SomeName")%>
<script>myfunction(<%# DataBinder.Eval(Container.DataItem, "SomeNumber")%>)</script>
</ItemTemplate>
</asp:Repeater>
I'm aware that most people won't repeat script tags like this, but I am using a small snippet of code from a third-party that you can place anywhere on a page to create a Flash object. You pass it a number so it knows which image gallery to display. No problems using several on one page.
To begin with, this worked fine, although I noticed the colours in Visual Web Developer indicated that it didn't really like the <%# being used inside a <script> tag. Intellisense was going a bit nuts in the code-behind too!
So what is the correct way to pass Dataset items into a script tag?
This perhaps? (Can't quite remember if the + signs should in fact be & signs though)
<%# "<script>myfunction(" + DataBinder.Eval(Container.DataItem, "SomeNumber") + ")</script>" %>
Another alternative syntax would be the following:
<%# Eval("SomeNumber", "<script>myfunction({0});</script>") %>
This uses the optional parameter where you can supply a format string.

asp.net - Use ascx as a layout template

This is my layout template (ascx without code behind)
<%# Control Language="C#" AutoEventWireup="true" Inherits="ws.helpers.LayoutUC" %>
<div>blah blah blah</div>
<ws:Panel runat="server" ID="left"></ws:Panel>
<ws:Panel runat="server" ID="main"></ws:Panel>
<ws:Panel runat="server" ID="right"></ws:Panel>
Modules will be added into ws:Panel later.
I also allow my user create their own ascx file to custom their page layout. And because of this i do a string replace all dangerous part like script tag (runat="server"), all asp.net html tag, <%, <%#, <#.... from their custom.
Im not worry about XSS, so dont comment on it, and ask why?
I want know your thinking about this. Is is safe? Is it scalable? Is it standard or a bad way?
Have a look at the INaminingContainer Interface http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx.
<asp:YourControl>
<LeftColumn>
<asp:Literal ID="literal1" runat="server" Text="User created literal" />
</LeftColumn>
</asp:YourControl>
In the .ascx from the users, they register your control and insert asp.net code into properties. In the 'YourControl' class you create placeholders and insert the markup set to a specific property into these placeholders. (e.g. everything between <LeftColumn> and </LeftColumn> will the inserted into
<asp:Placeholder ID="PlaceholderLeftColumn" runat="server"/>
Edit: I summed some of the TemplateContainer issue up and posted it here: http://www.tomot.de/en-us/article/2/asp.net/how-to-create-an-asp.net-control-that-behaves-as-a-template-container-to-nest-content-via-markup
You are allowing user-uploaded content; this is inherently unsafe and there are whole books dedicated to best practices. Given that you are doing it anyway, as long as you make sure you scrub the input, is it scalable? You are allowing creation of user-uploaded files on your site. How many will there be? How many users? What about load-balancing? This solution will not scale for many users, files, or servers.
It sounds like you are trying to create a simple CMS. Why not use one that exists currently, or adopt parts of an open source solution?

Simple HTML construction in ASP.NET?

A simple question, I think:
I want to put a tag into an ASP.NET app I've been asked to maintain, so I'm coming at this from a newbie point of view just tinkering around the edges without knowing a lot.
I wrote an old ASP application back in 1998, so I am just running on memory...
How do I write some output to the webpage?
I know I can use an
<asp:label id="blah">
but then I need to define a Label blah; in my code behind and then assign it.
I believe that I can put in-place:
<% Response.Write("sometext"); %>
and that will write sometext in the location within the page. (Am I correct?)
Lastly, I remember there was a syntax to the effect of
<%= "some string" %>
but I can't find the documentation on it, to say either it is deprecated, unadvised, or the rationale for such a decision.
I have tried googling for "ASP.NET grammar" but I can't even find a good description that "<%=" even exists, though it is mentioned in a few blogs.
For something simple, like inject the global version number, or the current date, then I can't see anything particularly wrong with in-place composition - it would save me defining 15 labels and having to initialise them all - though perhaps the asp:label approach could reference one global instance of a label?
Just asking for opinions on good practices :)
<%= string %> is perfectly valid ASP.NET syntax. The reason you will often find references to problems with using that is people use <%= (equivalent to Response.Write) when they should use <%# (for databinding) or vice-versa.
For example, we use it very extensively in our content managed site, where we pull in values from a global settings repository:
<%= SiteContext.Current.GetSetting("SiteTitle") %>
MSDN:
MSDN entry on <%= (this is under the JScript.NET section but still applies)
MSDN entry on <%#
Some others suggest <%= is not a "best practice" or a very good approach, but I strongly disagree with that sentiment. For an MVC-ish type site (especially a site that is template- or view-driven in some way), the most direct approach is frequently more effective than using server controls.
Just be mindful that when you use an <asp:Label /> it renders the .Text inside the <span> tag whereas an <asp:Literal /> adds no extraneous HTML to the string passed to it.
For example, if you were building a content management system and wanted to display user-driven HTML, a Label control would not correctly display the output from a WYSIWYG type rich textbox whereas a Literal control is the appropriate choice.
The <%= %> is the late-bound equivalent of the Literal's .Text property. The only difference here is when the value is placed in the page (aside from obvious syntax and separation of concerns paradigm) during the course of the page lifecycle.
Since the .Text property is on a control inherited from WebControl, it can be set/read/manipulated during any of the events following the control's Load event (wherever/whenever you load the control inside the page), but the <%= %> text cannot be directly read/used/manipulated by the code-behind without referencing some other control to get to it (like a containing div's InnerHtml property).
There are lots of options. You could use a single label, and string concatenate all the data you want displayed in that location.
You could create a user control with the layout you want and assign values that way.
You could inject it directly with response.write or the <%= %> syntax
You could create an HtmlGenericControl in your code behind (it's a div), add some text to it, and inject it into the pages controls collection.
Whatever you pick, try and go with the existing style of the coded page.
Look up the term "render blocks" for the <% %> syntax.
How about using
<asp:Literal id="z" text="goofy" runat="server" />?
Labels are usually used with forms.
You can also take full control of the rendering of your pages and controls and compose whatever you need to. You control the HTML, the order of rendering your controls, etc...
Go with the <asp:label /> (or a literal control if you want to customize some html in the content). Seriously. I'ts not that hard: when you put label in your markup visual studio will create it in the code-behind for you, so there's no extra work involved.
You could use the <%= "some string" %> syntax in web forms, but there can be issues when mixing that with the asp controls and there's a good reason new frameworks moved away from mixing logic like that in with your markup.

Resources