错误:在 MVC 中"model item passed into the dictionary is null"



遇到一个我不理解的错误:"传递到字典中的模型项为null,但此字典需要类型为"System"的非null模型项。小数'。"发生在视图中的这一行:

<td>@Html.EditorFor(model => model.Price)</td>

它应该为null。这是一个创建产品页面。这是代码:

public ActionResult Create()
        {           
            var items = new ProductItems();
            return View(items.Products);
VIEW :
@using Nop.Web.Models.Products
@model ProductItems
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)    
 <tr>
     <td>@Html.EditorFor(model => model.Price)  << error here
VIEW MODEL :
 public class ProductItems
    {
        public decimal Price { get; set; }
        public IEnumerable<Product> Products { get; set; } 

NOTE : I previously changed the View Model. It was :
@model Nop.Core.Domain.Catalog.Product
and it worked before I changed it.

导致此错误的原因是什么?感谢

您没有向视图传递任何内容,而是传递了一个空对象,因此它说model.price为null。如果你想填充你的编辑器模板,你必须说

public ActionResult Create()
{           
            ProductItems items = new ProductItems();
            items.Price = 15.99;
            return View(items);
 }

由于您正在传递视图类型为ProductItems的模型,因此您的视图也必须期望该类型。您应该将模型类放入Models文件夹中。在您的视图中调用的默认值为

@模型名称空间。模型。ProductItems,不确定模型类的路径。

@model  Nop.Web.Models.ProductItems
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)    
    <table>
        <tr>
            <td>@Html.EditorFor(model => model.Price)
            </td>
        </tr>
    </table>
}

我已经使用了你的代码,你的代码在我的处理中不会引起错误,但你也使用了类似的视图,请小心第一次清理构建。

相关内容

最新更新