Andrey Saleba
Andrey Saleba

Reputation: 2197

MVC dynamic pages from list

I have a page which represents data from ICollection<> model, it generates @Html.BeginForm() for each item in ICollection<> and shows data with @Html.Labels, and I want to create a link from each form to item details, so it will be like, when I press form with item with id=4, it sends Model.ElementAt(4) as a model to new page, and display it. How can I do that?

EDIT: I guess I need to add something like @Html.ActionLink("DetailsPage","Shops",shop)

@using WebShops
@model ICollection<WebShops.Shop>
@foreach (Shop shop in Model)
{
    using (Html.BeginForm())
    {
        @Html.Label(shop.name)
        @Html.Display(shop.name)
        <br />
        @Html.Label(shop.image)
        @Html.Display(shop.image)
        <hr />
    }
}

Upvotes: 0

Views: 105

Answers (2)

adricadar
adricadar

Reputation: 10209

To display a specific item there is no need for Html.BeginForm because it makes a POST request and you need to make a GET request.

You need to create a new Action that will make use of GET request.

public ActionResult Shop(string id)
{
     var shop =  //get shop by id from database
     return View(shop)
}

You call the new action like below.

@using WebShops
@model ICollection<WebShops.Shop>
@foreach (Shop shop in Model)
{
        @Html.Label(shop.name)
        @Html.Display(shop.name)
        <br />
        @Html.Label(shop.image)
        @Html.Display(shop.image)
        <hr />
        @Html.ActionLink("Display", "Shop","ControllerName", new {id = shop.id})
}   

Upvotes: 1

CodeCaster
CodeCaster

Reputation: 151594

You can do that using the object routeValues from this overload of Html.ActionLink:

@Html.ActionLink("DetailsPage","Shops", new { id = shop.ID })

This doesn't "send the model to the new page", it makes a link to Shops/DetailsPage/4, causing GET request when clicked.

So in the DetailsPage action method you'll have to look up the shop on ID again in order to display it.

Upvotes: 1

Related Questions