C# 获取所有项目并仅限制img标签的数量
我想要的是限制缩略图(img)的数量,保持foreach的原样 假设文件夹中有6个项目,我需要获取所有项目 但只有前两个图像标签 可能吗 这是我的密码C# 获取所有项目并仅限制img标签的数量,c#,asp.net-mvc,umbraco7,C#,Asp.net Mvc,Umbraco7,我想要的是限制缩略图(img)的数量,保持foreach的原样 假设文件夹中有6个项目,我需要获取所有项目 但只有前两个图像标签 可能吗 这是我的密码 @{ string folderPath = Server.MapPath("/media"); string[] files = Directory.GetFiles(folderPath + "/" + Model.Content.GetPropertyValue("Name")); } @foreach (string it
@{
string folderPath = Server.MapPath("/media");
string[] files = Directory.GetFiles(folderPath + "/" + Model.Content.GetPropertyValue("Name"));
}
@foreach (string item in files){
<li data-src="/media/@Model.Content.GetPropertyValue("Name")/@Path.GetFileName(item)" data-sub-html="">
<a href="">
<img src="/media/@Model.Content.GetPropertyValue("Name")/@Path.GetFileName(item)"/>
</a>
</li>
}
@{
字符串folderPath=Server.MapPath(“/media”);
string[]files=Directory.GetFiles(folderPath+“/”+Model.Content.GetPropertyValue(“名称”);
}
@foreach(文件中的字符串项){
}
所需的最终结果如下所示:
<li data-src="/media/806.png" data-sub-html="">
<a href="">
<img src="/media/806.png"/>
</a>
</li>
<li data-src="/media/853.png" data-sub-html="">
<a href="">
<img src="/media/853.png"/>
</a>
</li>
<li data-src="/media/089.png" data-sub-html="">
<a href="">
</a>
</li>
<li data-src="/media/931.png" data-sub-html="">
<a href="">
</a>
</li>
<li data-src="/media/061.png" data-sub-html="">
<a href="">
</a>
</li>
<li data-src="/media/735.png" data-sub-html="">
<a href="">
</a>
</li>
为什么不使用带有索引的for循环,然后执行if语句来限制显示
例如:
@{
string folderPath = Server.MapPath("/media");
string[] files = Directory.GetFiles(folderPath + "/" + Model.Content.GetPropertyValue("Name"));
}
@for(int i =0; i < files.Length; i++)
{
var item = files[i];
<li data-src="/media/@Model.Content.GetPropertyValue("Name")/@Path.GetFileName(item)" data-sub-html="">
<a href="">
// when index is 0 and 1 (first two), render image
@if(i <= 1)
{
<img src="/media/@Model.Content.GetPropertyValue("Name")/@Path.GetFileName(item)"/>
}
</a>
</li>
}
@{
字符串folderPath=Server.MapPath(“/media”);
string[]files=Directory.GetFiles(folderPath+“/”+Model.Content.GetPropertyValue(“名称”);
}
@for(int i=0;i
}
谢谢Alan,也许我没有正确地实现它,我遇到了一个错误,请您添加完整的代码来测试它。@我已经修改了答案1。将files.Count()
更改为files.Length
2。添加整个上下文。如果你仍然有错误,请用错误信息修改你的问题。谢谢,它有两个修改,在If(i>1)
之前添加@
,并将If(i>1)
更改为If(i@i),如果你是对的,很抱歉,我不知道我是怎么把条件弄错的。但是如果(i>