Home > DeveloperSection > Forums > upload files in asp.net mvc
ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    May-13-2013 2:25 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 1082  View(s)
Rate this:
Hi Expert!

How to upload file in ASP.NET MVC 4. I'm try as following line of code. but it returns always null value. 

.cshtml

<input type="file" name="file" id="file" />
controller.cs

   [HttpPost]
    public ActionResult Index(BookModel model, HttpPostedFileBase file, FormCollection values)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return View("Index", new BookModel());
            }

            if (file != null && file.ContentLength > 0)
            {                    
                var fileName = Path.GetFileName(file.FileName);                    
                var path = Path.Combine(Server.MapPath("~/img/"), fileName);
                file.SaveAs(path);

                model.ImageUrl = fileName;
            }


         //SendMail();
        }
        catch (Exception ex)
        {               
            return View("Index", new BookModel());
        }

        return View("Success");
    }

Please help me. 
Thanks in advance! 


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-13-2013 9:27 AM

Hi Ezra!

For upload files in asp.net MVC add form in you application as following.

enctype="multipart/form-data"

Don't want to miss updates? Please click the below button!

Follow MindStick