对象引用未设置为不存在 NULL 字段的对象实例

本文关键字:字段 对象 实例 NULL 不存在 设置 对象引用 | 更新日期: 2023-09-27 18:34:17

我的CMS 3.0项目中有以下代码

测量控制器.cs

private BuisnessSurveyEntities bsdb = new BuisnessSurveyEntities();
[HttpGet]
public ViewResult BizSurveyCDF()
{
  var bquery = from b in bsdb.form_field
               where b.ID != null        // int
               where b.DATID != null     // int
               where b.CAPTION != null   // string
               select new {b.ID, b.DATID, b.CAPTION};
  ViewData["BZQUESTIONS"] = new SelectList(bquery,"ID","DATID","CAPTION");
  return View();
}

form_field.cs模型

public virtual string ID {GET; SET;}
public virtual string DATID
{
  get{return _dATID;}
  set{_dATID = value;}
}
private string _dATID = "''''";

BizSurveyCDF.cshtml

@model IEnumberable<CMS.Models.form_field>
<table>
  <tr>
    <th>
      DATID
    </th>
    <th>
      CAPTION
    </th>
  </tr>
  @foreach(var item in Model)
  {
    <tr>
      <td>
        @Html.DisplayFor(modelItem => item.DATID)
      </td>
      <td>
        @Html.DisplayFor(modelItem => item.CAPTION)
      </td>
    </tr>
  }
</table>

现在我的问题是当我运行它时出现以下错误:

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

违规行是@foreach(模型中的变量项)

我已经浏览了整个表并用某些东西替换了所有 NULL 值,但仍然收到此错误。 到目前为止,我读到的所有内容都说它存在 NULL 值问题,但正如我已经说过的,我已经摆脱了所有空值。

任何帮助将不胜感激。

谢谢

对象引用未设置为不存在 NULL 字段的对象实例

尝试这样的事情,将模型传递给视图,不要在查询中创建新对象,选择完整的form_field对象。

public ViewResult BizSurveyCDF()
{
  var bquery = from b in bsdb.form_field
               where b.ID != null        // int
               where b.DATID != null     // int
               where b.CAPTION != null   // string
               select b;
  //ViewData["BZQUESTIONS"] = new SelectList(bquery,"ID","DATID","CAPTION");
  return View(bquery);
}

您没有在视图中使用 ViewData["BZQUESTIONS"]

您收到异常的原因可能是您的查询实际上没有返回任何值。因此,请确保查询在作为 SelectList 源传递之前至少包含一个元素。例如,尝试以下操作:

if(bquery.Any())
 {
   ViewData["BZQUESTIONS"] = new SelectList(bquery,"ID","DATID","CAPTION");
 }
else
{
   // Add code here to address there being of no element returned by the query 
}   
return View();
  1. 确保实际代码包含 IEnumerable 而不是 IEnumberable

  2. int 是一种值类型,因此永远不会为空。 这些地方的子句是不必要的。

  3. 您正在创建一个匿名对象,因此模型最终不是预期的类型,这就是为什么当您尝试 DivHenr 的解决方案时它失败的原因。 不要选择匿名对象。

  4. 此外,强制计算查询并将其传递给视图方法的模型参数(而不是视图数据)。

您的查询和操作应该是 -

  return View(  
       (from b in bsdb.form_field
       where b.CAPTION != null
       select b)
       .ToList() );