对象引用未设置为对象的实例-MVC 4-WebGrid导出

本文关键字:实例 -MVC 4-WebGrid 导出 对象 设置 对象引用 | 更新日期: 2023-09-27 18:27:45

我有一种将WebGrid导出到.csv文件的方法,但并非所有Survey都包含CompanyName,因此我得到错误"Object reference not set to a instance of a Object"

我该如何纠正这一点?

    public void DownloadCSV()
    {
        StringWriter sw = new StringWriter();
        sw.WriteLine("'"Project Number'",'"Location'"");
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=Survey" + DateTime.Today.ToShortDateString() + ".csv");
        Response.ContentType = "text/csv";
        var surveys = from s in SurveyDB.Surveys select s;
        foreach (var line in surveys)
        {
                sw.WriteLine(string.Format("'"{0}'",'"{1}'",'"{2}'"",
                                           line.projNo,
                                           line.locationName,
                                           line.Company.CompanyName
                                           ));
        }
        Response.Write(sw.ToString());
        Response.End();
    }

对象引用未设置为对象的实例-MVC 4-WebGrid导出

试试这个:

 sw.WriteLine(string.Format("'"{0}'",'"{1}'",'"{2}'"",
    line.projNo,
    line.locationName,
    (line.Company == null || line.Company.CompanyName == null) ? "" : line.Company.CompanyName
 ));

如果你正在使用实体框架,我建议你更新这行:

var surveys = from s in SurveyDB.Surveys select s;

收件人:

var surveys = from s in SurveyDB.Surveys.Include("Companies") select s;