Passing Model In Collection To Actionlink
Solution 1:
When you say return View();
, you aren't passing it a model. It's empty. So retrieve a model (usually from a database, but in your case just using an instance field) and pass that to the 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);
}
Your view should accept a ProductModel
as the model type.
@* 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>
You don't pass the product from the index view to the other view, you pass the ID in the URL, which will turn into a parameter for the action method (assuming you've used default routing). Change your link to this in your index view:
@Html.ActionLink(item.ProductName, "SingleProductView", new {Id = item.ProductId})
Your ProductModel
says you have a ProductId
property, and no ListPrice
property. I think you need to add a public double ListPrice {get; set;}
and then when you create your inventory, assign ID's, for example:
List<ProductModel> inventory = newList<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 },
};
The URL for accessing a product with an ID of 1 should be (assuming default routing) /Home/SingleProductView/1
.
By the way, you should rename ProductModel
to Product
. That makes it a little cleaner. And rename ProductName
to Name
. Look at the difference: ProductModel.ProductName
vs Product.Name
. Both are just as clear, but one is way more concise.
Post a Comment for "Passing Model In Collection To Actionlink"