收到错误:对象引用未设置为对象的实例

本文关键字:对象 实例 设置 错误 对象引用 | 更新日期: 2023-09-27 18:36:16

谁能帮我解决这个问题:

我需要在我的_DeliveryDetailsPatial.cshtml中显示动态数据。每次用户在"传递信息"页或"新地址"页中时都会调用此值。每次我要导航到这些页面中的任何一个时,我都会收到此错误:

对象引用未设置为对象的实例

我该如何解决这个问题?

谢谢!

这是我的代码:

_DeliveryDrtailsPartial

@model QuiznosOnlineOrdering.Models.StoreViewModel
<table id="orderTable" class="table">
        <tr>
            <td class="t">Item</td>
            <td class="t">Quantity</td>
            <td class="t">Item Price</td>
        </tr>
        @foreach (var item in Model.StoreAddress)
        {
            <tr>
                <td>@Html.DisplayFor(model => item.NOM)</td>
                <td>@Html.DisplayFor(model => item.ADRESSE)</td>
                <td>@Html.DisplayFor(model => item.VILLE)</td>
            </tr>
        }
    </table>

StoreViewModel

    public IEnumerable<Store> StoreAddress { get; set; }
    public IEnumerable<StoreHour> StoreHour { get; set; }
    public IEnumerable<ReferenceAcceptedPayment> StoreAcceptedPayment { get; set; }

DeliveryController

[HttpGet]
public ActionResult GetStoreDetails()
{
    StoreViewModel store = new StoreViewModel();
    store.StoreAddress = from s in db.Store
                             select s;
    return View();
}

收到错误:对象引用未设置为对象的实例

[HttpGet]
public ActionResult GetStoreDetails()
{
    StoreViewModel store = new StoreViewModel();
    store.StoreAddress = from s in db.Store
                             select s;
    return View(store);
}

您尚未通过模型

您实际上从未将模型注入到视图中。

[HttpGet]
public ActionResult GetStoreDetails()
{
    StoreViewModel store = new StoreViewModel();
    store.StoreAddress = from s in db.Store
                             select s;
    return View(store);
}

因此,当您尝试读取模型上的属性时,会出现异常,因为模型为 null。

你需要像这样传递模型

    [HttpGet]
public ActionResult GetStoreDetails()
{
    StoreViewModel store = new StoreViewModel();
    store.StoreAddress = from s in db.Store
                             select s;
    return View(store);
}
此外,以下是链接

,这些链接也将帮助您将视图传递到部分视图。

 return PartialView("_ViewPage",model);

在 asp.net mvc 视图和分部视图中设置模型