0

Code enter image description here

Error List

enter image description here

IDE: Visual Studio 2015
.NET Framework Version: 4.5.1
Project Template: ASP.NET MVC


Notes:

  • I already added the reference "System.Windows.Forms" to use OpenFileDialog class
  • I added "using System.Windows.Forms" (Btw, is this necessary if I already referenced the namespace?)
  • I cleaned and rebuilt the solution a few times
  • I even closed and reopened the whole project
Boris Sokolov
  • 1,723
  • 4
  • 23
  • 38
June
  • 15
  • 5

2 Answers2

1

Since you're using ASP.NET, you cannot use the OpenFileDialog class. It is for Windows Forms applications.

You'll need to use a File Upload input on your web page to upload the file. Here is one example of that from the MSDN using the FileUpload control.

Simple example using HTML input:

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

You'll have to update your code behind file as well.

EDIT: I didn't realize this was for an MVC project, not web forms.

You won't be able to use the asp:FileUpload control since you're not using webforms. However, it isn't hard to do it in MVC. Refer to this article for a comprehensive example. I've extracted some of the article below.

You'll have some kind of action to render the page and accept the posted file on your controller:

    [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();  
        }  
    }

And on your view, you'll have a form to upload and submit the file:

@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>                  
}  
Jack
  • 1,453
  • 1
  • 15
  • 35
0

You cant use OpenFileDialog, because MVC doesnt allow it, what you have to do is use

<input type="file"/>

On the front end

Edit: Just to be a bit more clear, think that you re trying to run a OpenFileDialog command on a computer which is a client, in web in general you cant use this kind of approach

here its more explained OpenFileDialog in cshtml

nalnpir
  • 1,167
  • 6
  • 14