MVC 5.0错误:对象引用未设置为对象的实例。

时间:2016-01-04 02:17:14

标签: asp.net asp.net-mvc

我正在使用MVC音乐商店模型构建在线食品订购网站。原来的音乐商店很少有增强功能,但是我遇到了一个我无处寻找解决方案的问题。

我的购物车页面引发以下错误:对象引用未设置为对象的实例。 出现此错误的原因是:我的Food对象为null(这与Album类相似)。

 @foreach (var item in Model.CartItems)
        {
            <tr id="row-@item.RecordId">
                <td data-th="Product">
                    <div class="row">
                        <div class="col-sm-2 hidden-xs">
                            <img src='@Url.Content("~/Content/Images/Product/Product64x64_" + @item.FoodId.ToString() + ".png")' />
                        </div>
                        <div class="col-sm-10">
                            <h4 class="nomargin">@item.Food.descr_short.ToUpper()</h4>
                            <p>@Html.ActionLink(item.Food.descr_short, "Details", "Store", new { id = item.FoodId }, null)</p>
                        </div>
                    </div>
                </td>

1 个答案:

答案 0 :(得分:0)

  public class Food
{
    [Key]
    public int food_id { get; set; }

    [DisplayName("Short Desc")]
    [StringLength(50)]
    [Required(ErrorMessage = "A short description is required")]
    public string descr_short { get; set; }

    [DisplayName("Description")]
    [StringLength(5000)]
    [Required(ErrorMessage = "Food Description is required")]
    public string descr { get; set; }

    [DisplayName("Ingredient")]
    [StringLength(1000)]
    public string ingredient { get; set; }

    [DisplayName("Unit Size")]
    public int size_unit { get; set; }

    [DisplayName("Units Per Meal")]
    public int units_per_meal { get; set; }

    [DisplayName("Calories")]
    public int calories { get; set; }

    [DisplayName("Available From")]
    public DateTime available_from { get; set; }

    [DisplayName("Discontinued?")]
    public bool discontinued { get; set; }

    [DisplayName("Discontinued Date")]
    public DateTime? discontinued_dt { get; set; }

    [DisplayName("Price")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
    [UIHint("Currency")]
    public Decimal price { get; set; }

    [DisplayName("Vegetarian?")]
    public bool veg { get; set; }

    [DisplayName("Days Available")]
    public string daysAvailable { get; set; }
    public virtual List<OrderDetail> OrderDetails { get; set; }


}
 public class Cart
{
    [Key]
    public int RecordId { get; set; }
    public string CartId { get; set; }
    public int FoodId { get; set; }
    [Required(AllowEmptyStrings = true, ErrorMessage = " ")]
    [Range(0, 100, ErrorMessage = "Quantity must be between 0 and 100")]
    [DisplayName("Quantity")]
    public int Count { get; set; }
    public System.DateTime DateCreated { get; set; }
    public virtual Food Food { get; set; }
}