1

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

在下面的代码中,您可以看到我的控制器操作代码、查看页面和模型类。每次运行应用程序时,我都会收到错误消息:对象引用未设置为对象的实例。此消息出现在 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; }       
}
4

1 回答 1

4

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

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

像这样:

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
    }
}
于 2013-02-01T12:23:23.030 回答