对象参照未设置为分部视图上的对象的实例

本文关键字:对象 实例 视图 设置 | 更新日期: 2023-09-27 17:56:54

可能的重复项:
对象引用未设置为对象的实例 - 分部视图

在下面的代码中,您可以看到我的控制器操作代码,查看页面和模型类。每次运行应用程序时,我都会收到错误消息:对象引用未设置为对象的实例。此消息显示在"查看以 foreach(var item in (IEnumerable....) 开头的 lint "上。如何解决此问题?

控制器:

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; }       
}

对象参照未设置为分部视图上的对象的实例

如果您的分部视图总是循环遍历ViewData中的FileInfoModel集合,那么将其模型类型设置为IEnumerable<FileInfoModel>并将其发送到分部视图不是更好吗?

此外,您需要对 Model 进行空检查,因为在呈现分部视图时,您的集合似乎为 null。

这样:

public ActionResult Upload()
{          
    var model = new List<FileInfoModel>(){
         new FileInfoModel(){Name = "sa",Length = 5, LastWriteTime = DateTime.Now},
         new FileInfoModel(){Name = "saa",Length = 5, LastWriteTime = DateTime.Now}
        };
    return View(model);
}

然后在视图顶部设置模型类型:

<% model IEnumerable<FileInfoModel> %>

然后更改您的foreach

if (Model != null)
{
    foreach (var item in Model)
    {
       //do stuff
    }
}