列表中的MVC动态页面

时间:2015-03-19 08:08:23

标签: c# razor model-view-controller

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

编辑:我想我需要添加@ Html.ActionLink(“详情页面”,“商店”,商店)等内容。

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

2 个答案:

答案 0 :(得分:1)

您可以使用this overload of Html.ActionLink中的object routeValues

来实现这一目标
@Html.ActionLink("DetailsPage","Shops", new { id = shop.ID })

这并没有将模型发送到新页面&#34;,它会链接到Shops/DetailsPage/4,导致点击时发出GET请求。

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

答案 1 :(得分:1)

要显示特定项目,不需要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})
}