可能重复:
对象引用未设置为对象的实例 - 部分视图
在下面的代码中,您可以看到我的控制器操作代码、查看页面和模型类。每次运行应用程序时,我都会收到错误消息:对象引用未设置为对象的实例。此消息出现在 View lint 上,以foreach(var item in (IEnumerable....)
. 我该如何解决这个问题?
控制器:
public ActionResult Upload()
{
var FilesInfoData = new List<FileInfoModel>(){
new FileInfoModel(){Name = "sa",Length = 5, LastWriteTime = DateTime.Now},
new FileInfoModel(){Name = "saa",Length = 5, LastWriteTime = DateTime.Now}
};
ViewData["FilesInfoView"] = FilesInfoData;
return View();
}
看法:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<FileInfoModel>>" %>
<%@ Import Namespace="MembershipTest.Models"%>
<fieldset>
<legend>
Upload File:
</legend>
<% using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { @enctype="multipart/form-data"}))
{ %>
<span>Filename:</span>
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" />
<% } %>
</fieldset>
<div id="uploadTable">
<table border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>
Filename
</th>
<th>
Length
</th>
<th>
LastModified
</th>
</tr>
</thead>
<tbody>
<%
foreach (var item in ((IEnumerable<FileInfoModel>)ViewData["FilesInfoView"]))
{ %>
<tr>
<td>
<%: item.Name %>
</td>
<td>
<%: item.Length %>
</td>
<td>
<%: item.LastWriteTime %>
</td>
</tr>
<% } %>
</tbody>
</table>
</div>
模型:
public class FileInfoModel
{
public string Name { get; set; }
public double Length { get; set; }
public DateTime LastWriteTime { get; set; }
}