【问题标题】:An unhandled exception occurred while processing the request. I got this error when I wanted to list the products by category?处理请求时发生未处理的异常。当我想按类别列出产品时出现此错误?
【发布时间】:2020-11-05 22:02:18
【问题描述】:

这是我的标记和代码:

@model ProductDetailModel

<div class="row no-gutters">
    <div class="col-md-3">
        <img src="~/img/@Model.Product.ImageUrl" class="img-fluid">
    </div>
    <div class="col-md-9">
        
        <h1 class="mb-3">@Model.Product.Name</h1><hr>
        @foreach (var item in Model.Catgeories)
        {
            <a href="#" class="btn btn-link p-0 mb-3">@item.Name</a>
        }
        
        <div class="mb-3">
            <h4 class="text-primary mb-3">@Model.Product.Price</h4><i class="fas fa-lira-sign"></i>
        </div>
        <button type="submit" class="btn btn-primary btn-lg">Add to Cart</button>
    </div>
</div>
<div class="row">
    <div class="col-md-12">
        <p class="p-3">@Model.Product.Description</p>
    </div>
</div>

我收到此错误:

'Detail.cshtml'
“InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为“shopapp.webui.Models.ProductListViewModel”,但此 ViewDataDictionary 实例需要一个“shopapp.webui.Models.ProductDetailModel”类型的模型项。”

【问题讨论】:

  • 请发布在屏幕上显示此视图的控制器操作代码

标签: asp.net-mvc asp.net-core-mvc


【解决方案1】:

'InvalidOperationException:传递到 ViewDataDictionary 的模型项的类型为“shopapp.webui.Models.ProductListViewModel”,但此 ViewDataDictionary 实例需要一个“shopapp.webui.Models.ProductDetailModel”类型的模型项。'

这意味着您的 Details.cshtml 需要一个模型 ProductDetailModel,但您传递了一个模型 ProductListViewModel。请确保您的后端代码如下所示:

public async Task<IActionResult> Details(int? id)
{
    var model= new ProductDetailModel(){....};
    //...
    return View(model);
}

【讨论】:

  • 我在列出产品时没有遇到任何问题。但是在创建详细页面时,我根据产品类别定义了不同的模型。因此,我得到了这个错误。
  • emmm,你说的似乎是我在这篇文章中分享的。所以你现在通过修改模型来解决你的问题?如果是这样,你能接受我的回答吗?它也可以帮助其他人。参考:How to accept as answer.
【解决方案2】:

'ShopController' 公共 IActionResult 列表(字符串类别) {

       var productViewModel=new ProductListViewModel()
        {
            Products=_productService.GetProductsByCategory(category)
        };

        return View(productViewModel);
    }
public IActionResult Details(int? id)
    {
        if(id==null)
        {
            return NotFound();
        }
        Product product = _productService.GetProductDetails((int)id);

        if(product==null)
        {
            return NotFound();
        }
        return View(new ProductDetailModel{
            Product=product,
            Catgeories=product.ProductCategories.Select(i=>i.Category).ToList()
        });
    }

'ProductDetailModel'

public class ProductDetailModel
{
    public Product Product { get; set; }
    public List<Category> Catgeories { get; set; }
}

【讨论】:

    猜你喜欢
    • 2012-01-20
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    相关资源
    最近更新 更多