How to create two ContentPlaceHolder with the same ID in ASP.NET? - asp.net

I don't want to have two master pages so I'm trying to do this (left out the <% %> for readability):
if (a == b)
{
<asp:ContentPlaceHolder ID="X" runat="server" />
}
else
{
<div class="c">
<asp:ContentPlaceHolder ID="X" runat="server" />
</div>
}
But it won't let me:
Duplicate ContentPlaceHolder 'X' were found. ContentPlaceHolders require unique IDs.
So I tried to set the IDs with ID="<%= "X" %>" and no, won't let me either:
Server tags cannot contain <% ... %> constructs.
Then I tried <%# Eval("X") %> and nope:
The ID property of a control can only be set using the ID attribute in the tag and a simple value. Example: <asp:Button runat="server" id="Button1" />
Is there any way to achieve what I'm trying to do? I was thinking something like
echo '<asp:ContentPlaceHolder ID="X" runat="server" />'
Or some dynamic way to add the tag because apparently the parser can't identify the if else block which won't let two tags have the same ID.
I'm using MVC with the default view engine.

Have you tried like this:
<% var isAEqualB = a == b; %>
if (isAEqualB)
{
<div class="c">
}
<asp:ContentPlaceHolder ID="X" runat="server" />
if (isAEqualB)
{
</div>
}

Related

repeater how to avoid blank html

We currently have an application which we have a repeater
<asp:Repeater ID="rptOfficials" runat="server">
<ItemTemplate>
<tr>
<td>
<p class="officials">
<%#Eval("OffPosition") %> <%#Eval("FullName") %>
</p>
<p class="officials">
<%#Eval("Phone") %>
</p>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
The Phone field is not always supplied, when not there a blank paragraph tag is generated, we're thinking of changing
<p class="officials">
<%#Eval("Phone") %>
</p>
to either:
<p class="officials">
<asp:label id="lblPhone" runat="server"/>
</p>
or:
<p class="officials">
<%#GetPhone("OffId") %>
</p>
and then have either the label return the phone number with the paragraph tags wrapped around it, or have the function return it. Is there a better way to get around this?
It depends how your Binding model is composed but I suggest adding the logic in your property (Phone) on your page your (view)model (yes you can and should use ViewModels in web forms as well).
That way you keep logic outside the view.
public string Phone {
get {
return this.phone ?? string.Empty;
}
}
That way your logic stays nicely inside your view model and your view just takes care of binding it.
If you don't want to generate the -tag, you can add a boolean property to your model.
public bool DisplayPhone{
get {
return this.Phone == string.Empty;
}
}
You then need to bind it to the visible property as Halcyon mentioned. (note you need a runat="server" for this)
<p runat="server" class="officials" visible='<% #Eval("DisplayPhone") %>'>
<% #Eval("Phone") %>
</p>
I would not recommend using "display: none" since it will keep the space of the p tag. Instead, make the p tag a server tag and set its visibility to false.
<p runat="server" class="officials" visible='<% !string.IsNullOrEmpty(#Eval("Phone")) %>'>
<% #Eval("Phone") %>
</p>
Instead of using
<p class="officials">
<%#GetPhone("OffId") %>
</p>
I prefer generate <p class="officials">foo</p> inside GetPhone(), then you can return nothing when Phone is empty.
You can add small logic like the following -
<%# string.IsNullOrWhiteSpace(Eval("Phone").ToString()) ?
"" : ("<p class=\"officials\">" + Eval("Phone") + "</p>")%>
However, if you want to add more logic, I would like to suggest to use Repeater.ItemDataBound Event
try with this
<p class="officials" <%#string.IsNullOrEmpty(Eval("Phone").ToString())? "style='display:none;':''" %> >
<%#Eval("Phone") %>
</p>

How can I conditionally check a property in the .aspx file inside EpiServer:MenuList?

I'm building a menu in EpiServer where I only want to include items that is of a certain pagetype. If the repeated item has a pagetype that equals "X" then print it out, else don't do nothing.
<ItemTemplate>
<li>
<span class="menu-level-1">
<%# Container.CurrentPage.PageTypeName == "NameOfPageType" ? "Something": "" %>
<span class="menu-divider"></span>
</span>
...
..
.
I want to print out every (who meets the criteria) items pagename, i.e:
<EPiServer:Property PropertyName="PageName" runat="server">
What is the correct syntax for exceuting code rather than printing out "Something"?
You could go with either:
<%# Container.CurrentPage.PageTypeName == "NameOfPageType" ? Container.CurrentPage.PageName : "" %>
or wrap your Property control with a standard ASP.NET PlaceHolder control:
<span class="menu-level-1">
<asp:PlaceHolder runat="server" Visible=<%# Container.CurrentPage.PageTypeName == "NameOfPageType" %> >
<EPiServer:Property PropertyName="PageName" runat="server" />
</asp:PlaceHolder>
<span class="menu-divider"></span>
</span>
You can hook into the Filter event from the underlying PageTreeData control.
Try something like this
yourMenulistControl.Filter +=
(o, args) => new FilterCompareTo("PageTypeName", "YOURPAGETYPENAME")
.Filter(args.Pages);

How to display a default image if Eval ("Thumbnail") is null - asp .net

I'm trying to upload a default thumbnail image if user hasn't uploaded any thumbnail for their news article. Can you please help?
I tried at first, but it didn't work:
<%#Eval("Thumbnail")!=null ? Eval("Thumbnail"):"~/Images/test.jpg"%>" alt="<%#Eval("Title") %>"
I'm have the following code in a repeater:
<asp:Repeater ID="rptRotator" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<div class="widgetContent">
<img class="thumbNail" src="<%#Eval("Thumbnail") %>" alt="<%#Eval("Title") %>" />
<h4 style="width: 155px;">
<a href="/news/<%#Eval("PublicationDate","{0:yyyy/MM/dd}")%>/<%#Eval("UrlName") %>">
<%#Eval("Title") %></a></h4>
<div class="clear">
</div>
<span class="newsDate">
<%# Eval("PublicationDate", "{0:dd MMMM yyyy}")%></span>
<div class="widgetTextSummary">
<p>
<%#Eval("Summary").ToString().Substring(0,60)%>...</p>
</div>
</div>
</li>
</ItemTemplate>
<FooterTemplate>
</ul></FooterTemplate>
</asp:Repeater>
A simple way to do this is to create a public method that you can use to determine if the data item is null or not and set it accordingly. This way you wouldn't have to put all your code inline. You would then have something like this in vb .net in your code behind:
Public Function ProcessDataItem(myDataItemValue As Object) As String
If myDataItemValue Is Nothing Then Return "~/Images/test.jpg"
Return myDataItemValue.ToString()
End Function
And then call it in the repeater:
<%# ProcessDataItem(Eval("Title")) %>" alt="<%#Eval("Title") %>"
Also, I recommend using Container.DataItem instead of Eval as it creates less overhead. So in the end it would be something like this:
<%# ProcessDataItem(Container.DataItem("Title")) %>" alt="<%#Container.DataItem("Title") %>"
How about give your property Thumbail a default value?
Then when the Thumbnail hasn't been set to a non-null value the default image will be displayed, otherwise the users thumbnail will be shown.
One of the following should work:
<%# Eval("Thumbnail") ?? "/images/default.png" %>
<%# Eval("Thumbnail") == DBNull.Value ? "/images/default.png" : Eval("Thumbnail") %>
<asp:Image ID="imgProd" runat="server" src="<%#Eval('Thumbnail')"
onerror="this.onload = null; this.src='ImageurlORAnyImageHere.jpg';"/>

ASP.NET Repeater Eval

I am trying to execute the following code in a .aspx page:
<asp:Repeater ID="rptComentarios" runat="server">
<ItemTemplate>
<% if (Convert.ToInt32(Eval("int_tipo")) == 1)
{ %>
<div class="resp">
<div class="top">
</div>
<div class="cont-resp">
<h3>
<%# Eval("txt_nome") %></h3>
<p>
<%# Eval("txt_comentario") %></p>
</div>
</div>
<% }
else
{%>
<div class="usuario">
<div class="top">
</div>
<div class="cont-usuario">
<h3>
<%# Eval("txt_nome") %></h3>
<p>
<%# Eval("txt_comentario") %></p>
</div>
</div>
<% } %>
</ItemTemplate>
</asp:Repeater>
It throws a runtime exception in the first line:
<% if (Convert.ToInt32(Eval("int_tipo")) == 1)
System.InvalidOperationException: Databinding methods such as Eval(), XPath() and Bind() can only be used in the context of a databound control.
What's wrong? Any ideas?
I had a similar problem and the following code worked for me:
<asp:Repeater ID="rptComentarios" runat="server">
<ItemTemplate>
<asp:PlaceHolder ID="placeholderBlaBlaBla" runat="server" Visible='<%# Convert.ToInt32(Eval("int_tipo")) == 1 %>'>
Your optional HTML
</asp:placeholder>
Other HTML
</ItemTemplate>
</asp:Repeater>
Some more comments:
Please note that single quotes are used to define the value Visible attribute of asp:placeholder. I tried double quotes too and they didn't work.
Anytime you want to get some optionally displayed HTML you should use a control to show/hide it. asp:placeholder works fine for that purpose. Don't ever do <% if(..) { %> - this is evil.
<%# ... %> is used to calculate or display expressions inside a repeater. These expressions can be displayed as HTML or passed as attributes of server side controls. You can't use if inside it.
I think there needs to be a # sign for the enclosure <%# ..Eval...%>
Or try the full Eval version
<%# if (Convert.ToInt32(DataBinder.Eval(Container.DataItem, "int_tipo"))
== 1) { %>

Giving a custom UserControl an ID in rendered HTML

When I use a ASP:Calendar control, and give it an ID:
<asp:Calendar runat="server" ID="MyCal" />
It looks like this in the rendered html:
<table id="NameMangled_MyCal"... />
And I can access the element by ID in javascript like this:
var cal= document.getElementById("<%= MyCal.ClientID%>")
However, When I make a custom user control that has-a calendar:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WeeklyEventsCalendar.ascx.cs"
Inherits="WeeklyEventsCalendar" %>
<div>
<asp:Calendar runat="server" ID="InnerCal" Width="100%" OnDayRender="RenderCell" OnVisibleMonthChanged="ChangeMonth" Height="480px" />
</div>
And then give it an ID when I add it to my page...
<mvs:WeeklyEventsCalendar ID="WeeklyCal" runat="server" />
That ID doesn't show up anywhere in the rendered HTML. all I get is
<div> stuff </div>
When I want
<div id="NameMangled_WeeklyCal"> stuff <div>
What am I doing wrong?
UserControls only render their contents, nothing else. What you could do is
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WeeklyEventsCalendar.ascx.cs"
Inherits="WeeklyEventsCalendar" %>
<div id="<%= this.ControlID %>">
<asp:Calendar runat="server" ID="InnerCal" Width="100%" OnDayRender="RenderCell" OnVisibleMonthChanged="ChangeMonth" Height="480px" />
</div>

Resources