ASP Dot Net: How to repeat parts of HTML with minor differences on the page?

This is a really simple problem.

I have an HTML code:

<div> <img src="image1.jpg" alt="test1" /> </div> <div> <img src="image2.jpg" alt="test2" /> </div> <div> <img src="image3.jpg" alt="test3" /> </div> 

etc...

Data comes from the database (image name, alt text).

In JAVA, I would do something like:

save information in an array at the end.

For a presentation, I would scroll it with JSTL:

 <c:foeach items="${data}" var="${item}> <div> <img src="${item.image}" alt="${item.alt}" /> </div> </c:foreach> 

What is the best practice in ASP.net I just don't want to create a line with the HTML code in it in the "code behind", this is an ugly IMO.

+4
source share
3 answers

I will take a hit on this without seeing your code:

Check out the ASP: Repeater control. Meanwhile, binding your data (with your deviations) to it can do what you want.

Link 1 Link 2

<Edit:> Okay, now that I see your code, I can help you better. I would definitely use a repeater for this. I would do it as in an ASPX file (I might have some errors):

 <ASP:Repeater id="MyRepeater" runat="server"> <div> <img src="<%# Eval("Filename")>" alt="<$# Eval("AltText")>" /> </div> </ASP:Repeater> 

Then in your C # you could:

 List<ObjectWithFilenameAndAltText> foo = GoGetTheseObjects(); MyRepeater.DataSource = foo; MyRepeater.DataBind(); 

I may have some mistakes in this, but I hope this will make you move in the right direction. If you don’t have a dedicated object for your images, you can simply use a dictionary or list> and use the β€œkey” and β€œvalue” in your ASPX code.

+5
source

This is the equivalent markup for the .ASPX file:

 <asp:Repeater ID="imageList" Runat="server" EnableViewState="False"> <ItemTemplate> <div> <img src="<%# DataBinder.Eval(Container.DataItem, "ImageSrc") %>" alt="<%# DataBinder.Eval(Container.DataItem, "Alt") %>" /> </div> </ItemTemplate> </asp:Repeater> 

In the code, you must set the imageList.DataSource property and call imageList.DataBind ().

+2
source

I would recommend looking at the Repeater control.

In your example:

 <asp:Repeater ID="yourRepeater" runat="server"> <ItemTemplate> <div> <asp:Image ID="yourImage" runat="server" ImageUrl='<%# Eval("Url") %>' ToolTip='<%# Eval("Name") %>' /> </div> </ItemTemplate> </asp:Repeater> 

Then in your code behind:

 List<MockData> lst = new List<MockData>(); lst.Add(new MockData() { Name = "Picture 1", Url = "pic1.jpg" }); lst.Add(new MockData() { Name = "Picture 2", Url = "pic2.jpg" }); lst.Add(new MockData() { Name = "Picture 3", Url = "pic3.jpg" }); yourRepeater.DataSource = lst; yourRepeater.DataBind(); 
+1
source

Source: https://habr.com/ru/post/1304592/


All Articles