baros
baros

Reputation: 251

upload files in asp.net mvc

I'd like to upload a file in asp.net mvc. I've the following codes. But file returns always null value. Is there anything, I should try?

.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");
    }

Upvotes: 0

Views: 832

Answers (1)

x2.
x2.

Reputation: 9668

Add to form enctype="multipart/form-data"

Upvotes: 3

Related Questions