Skip to main content
 首页 » 编程设计

c#之对象引用未设置为局部 View 中对象的实例

2024年02月20日20pander-it

<分区>

Possible Duplicate:
Object reference not set to an instance of an object - Partial View

在下面的代码中,您可以看到我的 Controller 操作代码、 View 页面和模型类。每次运行应用程序时,我都会收到错误消息:未将对象引用设置为对象的实例。此消息出现在 View lint starts with foreach(var item in (IEnumerable....) 上。如何解决此问题?

Controller :

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