在asp.net mvc上传文件

时间:2013-05-13 08:16:28

标签: c# asp.net asp.net-mvc file-upload asp.net-mvc-4

我想在asp.net mvc上传一个文件。我有以下代码。但file始终返回null值。有什么,我应该试试?

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

1 个答案:

答案 0 :(得分:3)

添加到表单enctype="multipart/form-data"