I need to upload multiple files into web server using MVC3 with RAZOR. I have the following code. In the controller, I am getting zero as the file count. How to correct it to get the actual number of files being uploaded and to get the content?
public class MyFileController : Controller
{
public ActionResult MyFileProcessActionTest()
{
return View();
}
[HttpPost]
public ActionResult MyFileProcessActionTest(IEnumerable<System.Web.HttpPostedFileBase> files)
{
int fileCount = files.Count<System.Web.HttpPostedFileBase>();
return RedirectToAction("Index");
}
}
VIEW
@{
ViewBag.Title = "MyFileProcessActionTest";
}
<h2>MyFileProcessActionTest</h2>
@using (Html.BeginForm())
{
<input type="file" name="files" id="file1" />
<input type="file" name="files" id="file2" />
<input type="submit" />
}
READING:
- Binding HttpPostedFileBase using Ajax.BeginForm
-
ASP.NET MVC Uploading and Downloading Files
http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files - How do I Validate the File Type of a File Upload?
- MVC 3 file upload and model binding
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You must include the enctype attribute in the form tag to indicate that the form should include files.
@using (Html.BeginForm("YourAction", "Controller", FormMethod.Post, new {enctype="multipart/form-data"))
{
}
Method 2
change your form to match the following
@using(Html.BeginForm("action","controller",FormMethod.Post,new{encType = "multipart/form-data"})){
{
<input type="file" name="files[0]" id="file1" />
<input type="file" name="files[1]" id="file2" />
<input type="file" name="files[2]" id="file3" />
<input type="submit" />
}
indices 0,1,2 will allow modelbinder to bind to IEnumerable furthermore encType also has to be specified when posting files to the server
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0