0

我刚刚正确地进入 MVC,我被困在一个我认为相对简单的概念上。

所以,我有一个表格,其中发布到控制器(这很好),此时我有:

控制器

public ActionResult TestAction(int productId)
{
    // What to do here... ?
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestAction(FormCollection values)
{
    // Do work here and return the objects
    return View(Products);
}

看法

@foreach (var product in Model)
            {
                <tr>
                    <td>@product.Provider.Name</td>
                    <td>&pound;@product.MonthlyPremium</td>
                    <td>@Html.ActionLink("More Details", "TestAction", new { productId = product.ProductId })</td>
                    <td>Compare</td>
                </tr>
            }

// I want the singular product details to be displayed here, under the product list... but how?!

现在,我想要的是当您单击“更多详细信息”(ActionLink)时,将显示产品详细信息,它们是单个 Product 对象的一部分。我从 GET 中调用了 TestAction 控制器,但是如何保留产品视图并显示单个产品的详细信息?将这个单一的产品分配给 ViewBag 并这样做?那么,对于产品列表,缓存原始列表并使用该缓存?

我希望通过回发来完成此操作,因为这是针对我网站的非 JS 版本的。

当然必须有更好的方法来做到这一点,或者我是不是已经被 ViewState 养得太久了?

4

1 回答 1

1

您可以为模型添加一个属性,例如bool ViewDetail,并在控制器中为与参数对应的项目设置该属性productId

public ActionResult TestAction(int productId)
{
    // TODO: error checking
    Products.Single(m => m.ProductId == productId).ViewDetail = true;
    return View(Products);
}

并将其显示在您的视图上:

var productDetail = Model.SingleOrDefault(m => m.ViewDetail == true);
if (productDetail != null)
{
    // Display product details
}

或者您可以更改您的模型以包含:

public class ProductsWithDetailModel
{
    public IEnumerable<Product> Products { get; set; }  // to loop over and display all products
    public Product DetailProduct { get; set; }          // to display product details, if not null
}

然后再次DetailProduct根据productId参数设置,如果不为null,则显示在视图中。

于 2012-11-22T16:45:59.070 回答