我试图在我的视图中传递多个模型,但我得到了以下错误Object引用未设置为对象的实例



嗨,我正在尝试将多个模型传递到我的MVC视图中。我已经创建了一个视图模型类,我正在GetDeviceSpecificationData((方法中从数据库中获取数据,并将其传递到Action Result GetDeviceSpecification((中的视图中。

@foreach (var spec in Model.myDeviceSpecifications)

错误是对象引用未设置为对象的实例。类型为"System"的异常。App_Web_eervchlw.dll中出现NullReferenceException,但未在用户代码中处理

我的ViewModelClass

public class InventoryViewModel
{
    public List<DeviceSpecifications> myDeviceSpecifications { get; set;}
}

从我的数据库获取设备规格数据的方法

public List<DeviceSpecifications> GetDeviceSpecificationData()
    {
        var myDeviceSpecifications = db.DeviceSpecifications.Include(d => d.Specification).Include(d => d.Value).Include(d => d.DSID).Include(d => d.SpecID).Include(d => d.DeviceID);
        return myDeviceSpecifications.ToList();
    }

我的行动结果

public ActionResult GetDeviceSpecification()
{
    InventoryViewModel mymodel = new InventoryViewModel();
    mymodel.myDeviceSpecifications = GetDeviceSpecificationData();
    return View(mymodel);
}

和我的视图

div class="form-group">
        @Html.LabelFor(model => model.myDeviceSpecifications, "Specification", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <select id="devspec">
                @foreach (var spec in Model.myDeviceSpecifications)
                {
                    <option value="@spec.SpecID">@spec.Specification</option>
                }
            </select>
        </div>
    </div>

在InventoryViewModel类中,您声明了一个列表,但没有初始化它。
解决方案是创建一个构造函数并最小化列表

public class InventoryViewModel
{
   public List<DeviceSpecifications> myDeviceSpecifications { get; set;}
   public InventoryViewModel()
   {
      myDeviceSpecifications = new List< DeviceSepecifications >();
   }
}

每当你有一个列表,总是按照这个方法。

相关内容

最新更新