【问题标题】:Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'无法将“System.String”类型的对象转换为“System.Collections.Generic.List`1[System.String]”类型
【发布时间】:2014-03-14 20:21:31
【问题描述】:
protected void File_Upload(object sender, AjaxFileUploadEventArgs e)
{   
    List<String> pathlist = null;
    if (Session["UploadedPath"] != null)
    {
        pathlist = (List<String>)Session["UploadedPath"];
    }
    else
    {
        pathlist = new List<string>();
    }
    string filename = e.FileName;
    string path = "~/Documents/" + filename;
    this.AjaxFileUpload1.SaveAs(Server.MapPath(path));
    pathlist.Add(path);
    Session["UploadedPath"] = pathlist;
}

我遇到这样的错误

无法将 System.String 类型的对象转换为 System.Collections.Generic.List1[System.String]. 类型

如何将多个上传的文件保存到数据库中

【问题讨论】:

  • Session["UploadedPath"]里面的值是什么?
  • Session["UploadedPath"]的数据类型是什么
  • 在你的项目中完整搜索字符串 Session["UploadPath"],我敢打赌你会找到一个将它设置为字符串而不是列表的地方
  • Session["UploadedPath"] 的@SaddamAbuGhaida 数据类型始终为object。这取决于该特定对象的值。
  • @Sachin 我认为 SaddamAbuGhaida 指的是 underlying 类型...

标签: c# asp.net


【解决方案1】:

在我看来,您的 UploadedPath 变量是 string,而不是 List&lt;string&gt;,因此您无法执行以下转换

pathlist = (List<String>)Session["UploadedPath"];

您需要确保当您设置UploadedPath 时,它绝对List&lt;string&gt; 的一个实例,而不是string

【讨论】:

    【解决方案2】:

    你确定 'Session["UploadedPath"];'包含一个列表类型值?。我认为它包含一个字符串值。

    pathlist = (List<String>)Session["UploadedPath"]; 
    

    将返回上述异常。

    请重新检查您存储在“UploadedPath”会话中的值并确保其为列表类型

    希望以下代码对您有所帮助。但请确保您是否在 Session["UploadedPath"];之前,请确保它是 List 类型。

    我不熟悉 AjaxFileUpload,如果 'e' 一次只包含一个文件,则以下将起作用。但是如果它包含多个文件,则必须循环遍历并将每个文件添加到“路径列表”中,然后将其保存到会话中

    protected void File_Upload(object sender, AjaxFileUploadEventArgs e)
    {   
        List<String> pathlist =  new List<String>();
    
        if (Session["UploadedPath"] != null)
        {
           pathlist = (List<String>)Session["UploadedPath"];
        }
    
        string filename = e.FileName;
        string path = "~/Documents/" + filename;
        this.AjaxFileUpload1.SaveAs(Server.MapPath(path));
        pathlist.Add(path);
        Session["UploadedPath"] = pathlist;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-24
      • 2012-09-07
      • 1970-01-01
      • 2013-08-15
      • 2022-08-09
      • 1970-01-01
      • 2021-04-26
      • 2017-03-04
      相关资源
      最近更新 更多