Search code examples
c#asp.net-mvcumbraco7

Get all the items and limit the number of the img tags only


What i'm looking for is to limit the number of the thumbnails (img) only and keep the foreach as it is.

Let's say that I have 6 items in the folder, I need to get all the items but only the first 2 of the image tags.

Is that possible?

Here's my code,

@{
    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>
} 

The final result needed looks like the following:

<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>

Solution

  • why not use a for loop with index and then do a if statment to limit display?

    such as:

    @{
        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>
    }