I believe that I couldn’t find a proper title to explain my problem but I think this is the best possible short explanation.
Please let me explain the details.
I want to show a list of my pictures on a page and using a @foreach loop on MVC 3.
Partial View of this list as below:
@model IEnumerable<Picture>
@foreach (var item in Model)
{
<a href="@item.PicId">
<img height="35px" style="padding-top:3px" src="ImageHandler.ashx?id=@item.PicId" id="pictureMy" />
</a>
}
As you may understand I am sending a list to this partialview and it is placing the pictures on a single column.
It is working without any problem but I want to show 3 pictures for each row but couldn’t manage.
Any guidance will be very appreciated.
Thanks in advance for your helps.
You could group them by 3:
But honestly this grouping is not something that should be done in the view. You should define a view model and then have your controller action perform the grouping and return the view model.
So let’s start by defining our view models:
then the controller action:
then the corresponding view:
then the corresponding display template for the
GroupedPicturesViewModeltype (~/Views/Shared/DisplayTemplates/GroupedPicturesViewModel.cshtml):and finally the display template for the
PictureViewModeltype (~/Views/Shared/DisplayTemplates/PictureViewModel.cshtml):One final thing that’s bugging me is this anchor. Looks ugly. Don’t you think? Looks like spaghetti code.
Let’s improve it by writing a custom, reusable HTML helper which will render those pictures:
and then in the display template we will simply have:
And that’s pretty much it. No need to write loops. Everything works by convention.