0

我找不到我的问题的解决方案,如下所示:我正在 ASP.net 中创建一个 MVC 在线商店。在我尝试将商品放入购物车之前,一切正常。然后我得到“对象引用未设置为对象的实例”错误。我尝试了几种解决方案,为其他用户解决了这个问题,但不幸的是没有任何运气。如果您需要更多我的代码,请告诉我:

namespace Oblig2.Models
{
    public class HandlevognViewModel
    {
        public List<Handlevogn> VognItems { get; set; }
        public decimal VognTotal { get; set; }
    }
}
@model Oblig2.Models.HandlevognViewModel

@{
    ViewBag.Title = "Handlevogn";
}

<h2>Handlevogn</h2>

<p class="button"> @Html.ActionLink("Til Kassen", "AdresseBetale", "Kassen")</p>

<table>
    <tr> 
        <th>Vare Navn</th>
        <th>Pris </th>
        <th>Antall </th>
    </tr>

    //This is where the error occurs.
    @foreach (var item in Model.VognItems)
    {
        <tr>
            <td>@item.Produkt.VareNavn</td>
            <td>@item.Produkt.Pris</td>
            <td>@item.Antall</td>
        </tr>
    }
</table>
namespace Oblig2.Controllers
{
    public class VarerController : Controller
    {
        private ButikkDBContext db = new ButikkDBContext();

        public ActionResult index()
        {
            return View(db.Produkt.ToList());
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
        }
    }
}

    namespace Oblig2.Controllers
    {
        public class HandlevognController : Controller
        {
            ButikkDBContext db = new ButikkDBContext();

            public ActionResult index()
            {
                var vogn = Vogn.GetVogn(this.HttpContext);

                var viewModel = new HandlevognViewModel
                {
                    VognItems = vogn.GetVognItems(),
                    VognTotal = vogn.GetTotal()
                };

                return View(viewModel);
            }

            public ActionResult LeggTil(int id)
            {
                var nyVare = db.Produkt.Single(vare => vare.VareNr == id);
                var vogn = Vogn.GetVogn(this.HttpContext);
                vogn.LeggTilHandleVogn(nyVare);

                return RedirectToAction("index");
            }

            [ChildActionOnly]
            public ActionResult VognSammendrag()
            {
                var vogn = Vogn.GetVogn(this.HttpContext);
                ViewData["VognAntall"] = vogn.GetAntall();
                return PartialView("VognSammendrag");
            }

        }
   }
4

1 回答 1

1

在您的模型中,添加一个私有字段:

private List<Handlevogn> vognitems = new List<Handlevogn>();
public List<Handlevogn> VognItems { get { return vognitems; } set { vognitems = value; }

VognItems 为空,因为您尚未实例化它。

于 2013-11-02T13:07:35.410 回答