将集合中的模型传递给 actionlink

Passing model in collection to actionlink

我觉得这是一个非常基本的问题。我想要实现的是将对象集合显示为 links。当我单击 link 时,我希望转到该特定对象的详细信息。

我可以在索引视图上显示项目 link 的集合,但是当我单击一个项目 link 时,我可以显示 SingleProductView,但不能在那里显示该特定项目的变量。

是否可以通过 html.actionlink 将特定项目传递给视图?或者,是否可以将该特定项目传递给另一个将显示视图的操作?

模特:

public class ProductModel
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
}

家庭控制器:

public class HomeController : Controller
{

    List<ProductModel> inventory = new List<ProductModel>() {
        new ProductModel { ProductName = "White T-Shirt", ProductDescription = "White T-Shirt", ListPrice = 10 },
        new ProductModel { ProductName = "Black T-Shirt", ProductDescription = "Black T-Shirt", ListPrice = 10 },
    };

    public ActionResult Index()
    {
        return View(inventory);
    }

    [HttpGet]
    public ActionResult SingleProductView()
    {
        return View();
    }
}

索引视图:

   @if(Model != null)
       {
            <ul>
            @foreach (ProductModel item in Model)
            {
                <li>
                    @Html.ActionLink(item.ProductName, "SingleProductView")
                </li>
            }
            </ul>
       }

当您说 return View(); 时,您并不是在传递模型。它是空的。因此检索一个模型(通常来自数据库,但在您的情况下只使用实例字段)并将其传递给视图。

[HttpGet]
public ActionResult SingleProductView(int id)
{
    //From the inventory, retrieve the product that has an ID that matches the one from the URL (assuming default routing)
    //We're using Linq extension methods to find the specific product from the list.
    ProductModel product = inventory.Where(p => p.ProductId == id).Single();

    //Send that product to the view.
    return View(product);
}

您的视图应接受 ProductModel 作为模型类型。

@* Declare the type of model for this view as a ProductModel *@
@model ProductModel

@* Display the product's name in a header. Model will be an instance of ProductModel since we declared it above. *@
<h2>@Model.ProductName</h2>

@* Display the product's description in a paragraph *@
<p>@Model.ProductDescription</p>

您不会将产品从索引视图传递到其他视图,而是在 URL 中传递 ID,它将变成操作方法的参数(假设您使用的是默认值路由)。在索引视图中将 link 更改为:

@Html.ActionLink(item.ProductName, "SingleProductView", new {Id = item.ProductId})

你的 ProductModel 说你有 ProductId 属性,没有 ListPrice 属性。我认为您需要添加 public double ListPrice {get; set;},然后在创建库存时分配 ID,例如:

List<ProductModel> inventory = new List<ProductModel>() {
    new ProductModel { ProductId = 1, ProductName = "White T-Shirt", ProductDescription = "White T-Shirt", ListPrice = 10 },
    new ProductModel { ProductId = 2, ProductName = "Black T-Shirt", ProductDescription = "Black T-Shirt", ListPrice = 10 },
};

用于访问 ID 为 1 的产品的 URL 应该是(假设默认路由)/Home/SingleProductView/1

顺便说一下,您应该将 ProductModel 重命名为 Product。这使它更干净一点。并将 ProductName 重命名为 Name。查看差异:ProductModel.ProductNameProduct.Name。两者都一样清楚,但一个更简洁。