列表中的 MVC 动态页面

MVC dynamic pages from list

我有一个页面代表来自 ICollection<> 模型的数据,它为 ICollection<> 中的每个项目生成 @Html.BeginForm() 并用 @Html.Labels 显示数据,我想从每个表单到项目详细信息创建一个 link,就像当我按下带有 id=4 项目的表单时,它会将 Model.ElementAt(4) 作为模型发送到新页面,并显示它。我该怎么做?

编辑:我想我需要添加类似@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 />
    }
}

您可以使用 this overload of Html.ActionLink 中的 object routeValues 来做到这一点:

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

这不是 "send the model to the new page",而是 link 到 Shops/DetailsPage/4,点击时会产生 GET 请求。

因此在 DetailsPage 操作方法中,您必须再次查找 ID 上的商店才能显示它。

要显示特定项目,不需要 Html.BeginForm,因为它会发出 POST 请求,而您需要发出 GET 请求。

您需要创建一个将使用 GET 请求的新操作。

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

你像下面这样调用新的动作。

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