当我尝试在视图中呈现NullPointerException
时,出现@Model.Columns
错误。我使用的是LinqToExcel。
相关代码部分:
型号:
namespace steer.Models
{
public class UpFile
{
// Irrelevant properties (name,size,filetype) omitted
public IEnumerable<string> Columns { get; set; }
public IEnumerable<LinqToExcel.Row> Rows { get; set; }
public class UpFileDBContext : DbContext
{
public DbSet<UpFile> UpFiles { get; set; }
}
}
}
查看:
@model steer.Models.UpFile
@foreach (var item in Model.Columns)
{
<th>@item</th>
}
控制器:
UpFile up = new UpFile();
// Name, size, filetype binding omitted
// Here I attempt to bind Columns and Rows from uploaded Excel file
var excel = new ExcelQueryFactory(AppDomain.CurrentDomain.BaseDirectory + "Uploaded\\" + up.Name);
var firstSheet = excel.GetWorksheetNames().First();
// Rows is IEnumerable
up.Rows = from c in excel.Worksheet(firstSheet)
select c;
// GetColumnNames returns a List. up.Columns property is IEnumerable.
up.Columns = excel.GetColumnNames(firstSheet);
db.UpFiles.Add(up);
db.SaveChanges();
Name
,size
,filetype
设置得很好。但columns
和rows
属性始终为空。
Excel文件的提取也可以正常工作,因为我可以直接将Excel行成功发送到视图。只有当我尝试引用我遇到麻烦的属性时才会这样。
// GET: files/details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
UpFile upFile = db.UpFiles.Find(id);
if (upFile == null)
{
return HttpNotFound();
}
return View(upFile);
}
另外!!当我在db.SaveChanges()
插入断点时,所有数据都在那里