简体   繁体   English

在@Razor之类的aspx页面中呈现动态HTML控件数?

[英]Render dynamic # of HTML controls in aspx page like @Razor?

I know we can put a placehold on aspx page, then add controls dynamically from backend code. 我知道我们可以在aspx页面上放一个位置,然后从后端代码动态添加控件。 Is there a way in aspx page that is similar to @razor engine that we can add html control directly in aspx page? 在aspx页面中是否有一种类似于@razor引擎的方法,我们可以直接在aspx页面中添加html控件?

<% 
    int count = GetImageCount();
    for (int k = 0; k < count; k++)
    {
        string id = "img_" + k.ToString();
%>
        <asp:Image runat="server" ImageAlign="Middle" />

<%                    
    }                   
%>

We can use above code to add multiple Image control in aspx page, but how can we set them with different id and src? 我们可以使用上面的代码在aspx页面中添加多个Image控件,但是如何为它们设置不同的id和src?

Or, we can not do this in aspx directly? 或者,我们不能直接在aspx中执行此操作?

thanks 谢谢

You cannot set ID for server controls dynamically. 您不能动态设置服务器控件的ID。 Also, as far as I am aware of, setting ImageUrl direclty in aspx for the control in for loop, like in your code, might not be possible - you should probably take a look and asp:Repeater control. 另外,据我所知,可能无法在aspx中为for循环中的控件设置ImageUrl direclty,就像在您的代码中一样-您可能应该看一下asp:Repeater控件。

To achieve what you want, you might find useful this piece of code, using HTML <img> control (as @Grundy suggested), instead of asp:Image control: 为了实现所需的功能,您可能会发现使用HTML <img>控件(如@Grundy建议)而不是asp:Image控件,可以使这段代码有用:

<% int count = 5;
    for (int i = 0; i < count; i++)
    {
        string id = "id_" + i;
        string imageUrl = "/Images/img_" + i;
%>
    <img id="<%=id%>" src="<%=imageUrl%>"/>
<% 
    }
%>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM