【问题标题】:"OpenFileDialog" class does not contain definitions for "ShowDialog()" and "FileName"“OpenFileDialog”类不包含“ShowDialog()”和“FileName”的定义
【发布时间】:2018-10-18 12:19:29
【问题描述】:

代码

错误列表

IDE: Visual Studio 2015
.NET Framework 版本: 4.5.1
项目模板: ASP.NET MVC


注意事项:

  • 我已经添加了引用“System.Windows.Forms”来使用 OpenFileDialog 类
  • 我添加了“使用 System.Windows.Forms”(顺便说一句,如果我已经引用了命名空间,这是否必要?)
  • 我清理并重建了几次解决方案
  • 我什至关闭并重新打开了整个项目

【问题讨论】:

  • 请不要将代码添加为图像,而是使用代码块。
  • 同样适用于错误消息。将它们添加为图像会使问题难以搜索。

标签: c# asp.net-mvc visual-studio


【解决方案1】:

由于您使用的是 ASP.NET,因此您不能使用 OpenFileDialog 类。它适用于 Windows 窗体应用程序。

您需要在网页上使用文件上传输入来上传文件。 Here is one example 来自 MSDN 使用 FileUpload 控件。

使用 HTML 输入的简单示例:

<input type="file" name="file" />

您还必须更新您的代码隐藏文件。

编辑: 我没有意识到这是针对 MVC 项目,而不是 Web 表单。

您将无法使用 asp:FileUpload 控件,因为您没有使用网络表单。但是,在 MVC 中做到这一点并不难。 Refer to this article 是一个全面的例子。我摘录了下面的一些文章。

您将有某种操作来呈现页面并在您的控制器上接受发布的文件:

    [HttpGet]  
    public ActionResult UploadFile()  
    {  
        return View();  
    }  
    [HttpPost]  
    public ActionResult UploadFile(HttpPostedFileBase file)  
    {  
        try  
        {  
            if (file.ContentLength > 0)  
            {  
                string _FileName = Path.GetFileName(file.FileName);  
                string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);  
                file.SaveAs(_path);  
            }  
            ViewBag.Message = "File Uploaded Successfully!!";  
            return View();  
        }  
        catch  
        {  
            ViewBag.Message = "File upload failed!!";  
            return View();  
        }  
    }

在您看来,您将有一个表单来上传和提交文件:

@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { enctype="multipart/form-data"}))  
{         
    <div>  
        @Html.TextBox("file", "", new {  type= "file"}) <br />       
        <input type="submit" value="Upload" />      
        @ViewBag.Message        
    </div>                  
}  

【讨论】:

    【解决方案2】:

    你不能使用OpenFileDialog,因为MVC不允许,你要做的就是使用

    <input type="file"/>
    

    前端

    编辑:为了更清楚一点,认为您正在尝试在作为客户端的计算机上运行 OpenFileDialog 命令,通常在网络中您不能使用这种方法

    这里有更多解释OpenFileDialog in cshtml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多