Binding Eval with an ImageURL in ASP.NET - c#

I'm trying to bind an image using Eval() with VB.NET and ASP.NET, but am running into issues:
Code snippet
<bri:ThumbViewer Id="Th1" runat="server"
ImageUrl='<%# Eval("Name", "~/SiteImages/ram/3/{0}") %>'
Height="100px"
Width="100px"
/>
I set strImagePath in the code-behind as:
strImagePath ="~/SiteImages/ram/3/"
How can I replace:
~/SiteImages/ram/3/{0}
with the variable strImagePath?

simply use
<asp:Image id="abc" ImageUrl =<%# string.Format("~/SiteImages/ram/3/{0}",Eval("imagepath"))%>
imagepath could be from datatable or cs

I personally prefer to do these things in the codebehind directly like
<bri:ThumbViewer ID="thumbViewer" runat="server" ... />
and then in the codebehind you have some initialize or DataBind() method where you write
thumbViewer.ImageUrl= Path.Combine(ImagePath, Name); //or something similar, you have to check
This because especially when you develop in a team it is quite inconvenient and error-prone if people do some bindings in the ASPX code directly using Eval(...) and some in the codebehind. I prefer using the codebehind because then you immediately see what's going on on the page by just looking on your code, while your ASPx code is just for layout, definition of controls (with properties) etc...

string strImagePath = "aPage.aspx";
string pathFormat = "~/SiteImages/ram/3/{0}";
string path = String.Format(path, strImagePath);
Thats a little bit verbose, but you get the idea. What you're looking for is the String.Format method.
You can read more about it over at MSDN -> String.Format
So in your case that would be:
<bri:ThumbViewer Id="Th1" runat="server" ImageUrl='<%# Eval("Name", String.Format("~/SiteImages/ram/3/{0}", strImagePath)) %>' Height="100px" Width="100px"/>
as long as strImagePath is set to public or protected in your codebehind

Can you just write (and forgive me if this is wrong) if it is constant:
<bri:ThumbViewer ImageUrl='~/SiteImages/ram/3/<%# Eval("Name")%>' Height="100px" Width="100px" Id="Th1" runat="server"/>
And if it isn't:
<bri:ThumbViewr ImageUrl='<#Eval("ImagePath + Name") %>' ... />
//And in your codebehid:
public property ImagePath { get; set; }
...
ImagePath = "...";

Related

Declarative Markup: Expression Builder

Is there a way to display the value of MyClass.SomeMessage in the expression builder <%$ $> of the label control below?
<asp:Label ID="lblMessage" runat="server"
Text="<%$ Is there a way to display the value of MyClass.SomeMessage here %>" />
public static class MyClass
{
public static string SomeMessage
{
get
{
string message = "This is some test message";
return message;
}
}
}
It there a real reason this is a serverside label?
<asp:Label ID="lblMessage" runat="server" Text="<%$ Is there a way to display the value of MyClass.SomeMessage here %>" />
If yes, then change <%$ to <%# use lblMessage.Databind() on the server side and you can see the value there.
Since it's a label, I would suggest using some html client side value and use "<%=MyClass.SomeMessage %>". You must not have the runat server though.

How to display a Navigation Property of a table inside a Data control like a FormView?

Ok I have a many to many relationship like this:
Walk = {WalkID, title, ...., (Navigation Properties) Features}
Feature = {FeatureID, featureName, description, (Navigation Properties) DogWalks}
I do of course have a junction table, but EF assumes this thus it is not shown in my edmx diagram:
WalkFeatures = {WalkID, FeatureID} //junction, both FK
So using LINQ with EF, I am now trying to grab the features for the Walk at WalkID=xx.
This is my formview:
<asp:FormView ID="FormView1" runat="server" ItemType="Walks.DAL.Walk" SelectMethod="FormView1_GetItem">
<ItemTemplate>
<h1><%# Item.Title %></h1>
...
</ItemTemplate>
</asp:FormView
<asp:Label ID="lbFeatures" runat="server" Text="Label"></asp:Label>
And selectMethod:
public Walks.DAL.Walk FormView1_GetItem([QueryString("WalkID")] int? WalkID)
{
using (WalkContext db = new WalkContext())
{
var walk = (from n in db.Walks.Include("Features")
where n.WalkID == WalkID
select n).SingleOrDefault();
foreach(var f in walk.Features){
lbFeatures.Text += f.FeatureName + "<br/>";
}
return walk;
}
}
The code runs fine, but is there a way that I can display the Walk.Features directly inside the <ItemTemplate> of the formview rather than using a label and a loop? Can the attribute be directly binded like the other properties in the .aspx page?
I have also used this new feature not that extensively but just gave it a try for this particular scenario and this is what I have:-
Simply return walk from FormView1_GetItem method and don't manipulate your label control there. Now, you can use a Repeater control to display the lbFeatures control (since it is going to repeat dynamically) like this:-
<ItemTemplate>
<h1><%# Item.Title %></h1>
<asp:Repeater ID="lbFeatures" runat="server" DataSource='<%# Item.Features%>'>
<ItemTemplate>
<asp:Label ID="lblTest" runat="server"
Text='<%# Eval("FeatureName") %>'></asp:Label>
<br />
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
As you can see I am able to assign the datasouce of repater control as Item.Features, then use the conventional approach to bind the label. This looks clean and simple :)

Trouble binding XML child to DataList using ReadXML()

I am trying to bind an ASP DataList control with the values returned from an XML file. What's somewhat unique is that I'm not loading the XML from a file, but rather using XMLTextReader() to load it as a string. The reason for this is that the XML will be built from values read from the database. Here's the code which takes (in this case a hard-coded) XML string, adds it to a DataSet and then binds the DataList control...
StringBuilder xml = new StringBuilder();
xml.Append("<product>");
xml.Append("<sku>241</sku>");
xml.Append("<prodID>2SIDED</prodID>");
xml.Append("<name>Product Name</name>");
xml.Append("<price>6.99</price>");
xml.Append("<description>Product Description</description>");
xml.Append("<standalone>1</standalone>");
xml.Append("<sellable>1</sellable>");
xml.Append("<product-type>10</product-type>");
xml.Append("<customization>");
xml.Append("<option1></option1>");
xml.Append("<option2></option2>");
xml.Append("<option3></option3>");
xml.Append("</customization>");
xml.Append("</product>");
using (XmlTextReader tr = new XmlTextReader(new StringReader(xml.ToString())))
{
var document = XElement.Load(tr);
string source = document.ToString();
DataSet dsProdList = new DataSet();
dsProdList.ReadXml(new StringReader(source));
prodDetail.DataSource = dsProdList;
prodDetail.DataBind();
}
Here's the DataList control...
<asp:DataList ID="prodDetail" runat="server" OnItemDataBound="prodDetail_ItemDataBound">
<ItemTemplate>
<div class="proddetail">
<asp:Image ID="Image" runat="server" width="480" height="325" AlternateText='<%#DataBinder.Eval(Container.DataItem, "name") %>'/>
<asp:HiddenField ID="hdnStandalone" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "standalone") %>' Visible="false" />
<asp:HiddenField ID="hdnSellable" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "sellable") %>' Visible="false" />
<asp:HiddenField ID="hdnTypeId" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "product-type") %>' Visible="false" />
<asp:HiddenField ID="hdnOption1" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "option1") %>' Visible="false" />
<asp:HiddenField ID="hdnOption2" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "option2") %>' Visible="false" />
<asp:HiddenField ID="hdnOption3" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "option3") %>' Visible="false" />
<asp:Label ID="lblDescription" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "description") %>'>
</div>
</ItemTemplate>
</asp:DataList>
This seems to be working fine until the code attempts to bind "option1" at that point I get the following exception:
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'option1'.
From what I can work out this definitely seems to be an issue with "option1" being a child of "customization". If I simply comment out the opening and closing "customization" tags, which effectively leaves the "option(s)" as children of "product" the code runs fine and I get the output I'm expecting.
Is there any way I can format the DataBinder.Eval() to see the child item? If so, I can't figure it out and hours of searching having been unsuccessful. Or should I be tackling this differently? Perhaps not using a DataSet? Any help is appreciated. Thanks.
You can try with xDoc and linq and anonymous type as,
prodDetail.DataSource = from item in xDoc.Descendants("product")
from needThis in item.Descendants("customization")
select new
{ ProductName = item.Element("sku").Value,
ID = item.Element("prodID").Value,
//----other properties----
Option1 = needThis.Element("option1").Value,
Option2 = needThis.Element("option2").Value,
//---and some more properties----
};
you have to make sure you give the property names of the anonymous object same as the property names you are expecting in the databind in datalist.

ASP.NET wrap an asp:HyperLink in <li>'s, from server-side

I have the next structure for a menu item:
class MenuItem
{
public string Path, Title;
}
I want to be able to Iterate an object of MenuItem[], creating a new object of asp:HyperLink on each iteration, and to add it to a <ul> list.
One thing that must happen is that each HyperLink will be inside a <li> tag.
How can I do that?
You can use a repeater. In the aspx:
<asp:Repeater ID="repMenuItems" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li><asp:HyperLink ID="lnkMenuItem" runat="server" Text='<%# Eval("Title") %>' NavigateUrl='<%# Eval("Path")%>'/></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
And in the codebehind:
repMenuItems.DataSource = arrMenuItem; // your MenuItem array
repMenuItems.DataBind();
Additionaly you should change your class code for using Public Properties instead of Public Members, like this:
public class MenuItem
{
public string Title {get;set;}
public string Path {get;set;}
}
I recommend you to read more about Properties in .NET, a nice feature for object encapsulation http://msdn.microsoft.com/en-us/library/65zdfbdt(v=vs.71).aspx
Hope this helps you

javascript server tag not well formed

i wish to pass 2 value to invoke my script but i failed to do so it return me server tag not well formed
asp:LinkButton ID="lnkname" runat="server" Text='<%#Eval("movieTitle") %>' Width='500px'
CommandName="cmdLink" PostBackUrl='~/videotest.aspx'
OnClientClick="setSessionValue('video','<%#Eval("movieTitle") %>');"
Try like this:
OnClientClick='<%# string.Format("setSessionValue(\"video\", {0});", Eval("movieTitle")) %>'
Or even better ensure that you properly encode the movie title using the JavaScriptSerializer class:
OnClientClick='<%# string.Format("setSessionValue(\"video\", {0});", new JavaScriptSerializer().Serialize(Eval("movieTitle"))) %>'
Yeah, I agree, what a horrible mess are those WebForms. You would probably externalize this into a function in your code behind:
public string FormatJs(object movieTitle)
{
return string.Format(
"setSessionValue(\"video\", {0});",
new JavaScriptSerializer().Serialize(movieTitle)
);
}
and then:
OnClientClick='<%# FormatJs(Eval("movieTitle")) %>'

Categories