2012-05-16 54 views
0

我在我的CMS 3.0项目下面的代码对象引用不设置到对象的实例与目前

SurveyController.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 = "\'\'"; 
没有NULL字段

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(以型号VAR项目)

我经历了整个表不见了,东西全部换成NULL值的和至今还在领受此错误。到目前为止,我读过的所有东西都说它有NULL值的问题,但正如我已经说过的,我已经摆脱了所有的空值。

任何帮助将非常感激。

感谢

+0

难道'bsdb'是'null'? – Oded

+0

可能是LINQ正在执行超出范围。所以我认为Oded很可能是对的。尝试对查询结果执行ToArray()或ToList(),然后将其交给视图? – Balthy

+0

你有form_field.cs模型中的CAPTION吗? – Damith

回答

2

尝试这样的事情,通过模型,视图,不产生在查询一个新的对象,选择完整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); 
} 

你是不是在你看来

+0

@HenkHolterman视图模型是一个IEnumberable hjgraca

+0

你是对的,我错过了。 –

+0

没有区别 –

0

为什么你得到的例外可能是你的查询没有返回任何值actually.So之所以使用计算机[“BZQUESTIONS”],确保该查询包含作为选择列表的source.For例如在传递前至少一个元素,尝试一些沿着这些路线:

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(); 
0
  1. 确保实际的代码包含IEnumerable的不IEnumberable

  2. int是一个值类型,因此不会为空。这些条款是不必要的。

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

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

您的查询和行动应该是 -

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