The model item passed into the
ViewDataDictionary
is of type'WebApp.Models.Order'
, but thisViewDataDictionary
instance requires a model item of type'System.Collections.Generic.List
1[WebApp.Models.Product]'.`
Models
Product.cs
namespace WebApp.Models
{
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Order.cs
using System.Collections.Generic;
namespace WebApp.Models
{
public class Order
{
public int OrderId { get; set; }
public List<Product> Products { get; set; }
public decimal Total { get; set; }
}
}
Controller
HomeController.cs
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;
namespace WebApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
List<Product> Products = new List<Product> {
new Product {
Name = "Mobile Phone",
Price = 300
},
new Product {
Name = "Laptop",
Price = 1000
},
new Product {
Name = "Tablet",Price = 600
}
};
Order order = new Order();
order.Products = Products;
order.Total = Products.Sum(product => product.Price);
return View(order);
}
}
}
Views
Relative view page: Index.cshtml
@model List<WebApp.Models.Product>
<ul>
@foreach (var Product in Model)
{
<li>@Product.Name</li>
}
</ul>
Partial view page: _Layout.cshtml
@model WebApp.Models.Order
<table border="1">
<tr>
<th>Product Name</th>
<th>Price</th>
</tr>
@foreach (var Product in Model.Products)
{
<tr>
<td>@Product.Name</td>
<td>@Product.Price</td>
</tr>
}
<tr>
<td><b>Total</b></td>
<td><b>@Model.Total</b></td>
</tr>
</table>
Layout setter page: _Viewstart.cshtml
@{
Layout = "_Layout";
}
An unhandled exception occurred while processing the request.
I don't know how to deal with it.
The view is expecting a list of products:
@model List<WebApp.Models.Product>
You are passing it an order:
return View(order);
If the rest of your view also uses the order, then it sounds like you just need to change your model declaration on the view:
@model WebApp.Models.Order
And loop through the products on that model:
@foreach (var Product in Model.Products)
What's strange is that you're trying to do this in your layout . Don't do that. The layout is just dressing around the page to be applied to every page. It shouldn't require anything from the model. The view itself should be bound to the model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.