locked
How to get item Id after displaying many pictures from foreach loop RRS feed

  • Question

  • User1242168447 posted

    I'm displaying many images in a view using foreach loop from Model, and the user need to click one of them and get details... then I need to load another page and show the details for the selected image according to his Id. But now How do I find the correct Id to display details for it. selected image must match the item Id in the Model

    foreach (var item in Model.OrderBy(x => x.Id))
                {
                    <div class="col-xs-18 col-sm-4">
                        <div class="thumbnail">
                            <div class="zoomImage">
                                @*<img style="width: 100%" src="https://cdn.pixabay.com/photo/2016/02/19/11/19/computer-1209641_1280.jpg">*@
                                @*<img style="width: 100%" src="@Html.DisplayFor(modelItem => item.Images[0])" alt="Image">*@
                                <img style="width: 100%" src="@Html.DisplayFor(modelItem => item.MainImage)" alt="Image">
        </div>
        </div>
        </div>
        }


    </div>

    Wednesday, October 23, 2019 6:29 PM

Answers

  • User475983607 posted

    This is an MVC question not Web API which is the subject of this forum.   Are you looking for a Web API solution?

    If we assume MVC, surround the image with a link which makes the image clickable.  A link cause the browser to do an HTTP GET. In other words, invoke a Get Action of your choice.

    @foreach (var item in Model.OrderBy(x => x.Id))
    {
    <div class="col-xs-18 col-sm-4">
    	<div class="thumbnail">
    		<div class="zoomImage">
    			<a href="@Url.Action("Home", "Index", new { id = item.Id })" >
    				<img style="width: 100%" src="@item.MainImage" alt="Image">
    			</a>
    		</div>
    	</div>
    </div>
    }

    The code above assumes @item.MainImage is the URL to the image.  The @Url.Action helper create a URL that uses the default route parameter; id.  The resulting HTML.

    <a href="/Home/Details/2">
       <img style="width: 100%" src="2" alt="Image">
    </a>

    The action that handles the HTTP GET request.

    [HttpGet]
    public ActionResult Details(int id)
    {
        return View();
    }

    I recommend going through the Getting Started with MVC tutorials as the tutorials cover standard programming patterns found in MVC.

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/getting-started

    https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 23, 2019 6:59 PM