Upload files with model data in MVC

Upload multiple files with model data in MVC is really very easy, when I started to test by uploading some files, I though it would be more complicated but it is really not. In my previous post ASP.Net MVC file upload, I promised to post soon about how to upload multiple files. When I was writing I thought why cannot add model data as well at the time of uploading the files.

We will create a simple expense detail page with multiple files, I created a very simple just two value property, expense description and amount, which will be stored into database and as many files as we want supporting to this expense.

alt text

So let's start by creating first our model

public class ExpenseModel
{
    [Required(ErrorMessage = "{0} is required")]
    [Display(Name = "Expense Description")]
    public string Description { get; set; }

    [Required(ErrorMessage = "{0} is required")]
    [Display(Name = "Amount")]
    public string Amount { get; set; }
}

We have not defined any property in our model to upload the file or list of files, we will discuss it why, once we will see our controller.

And here is the view HTML using Razor engine

@model MvcUploadMultipleFiles.Models.ExpenseModel

@{
    ViewBag.Title = "Expense With Documents";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Expense With Documents</h2>

@using (Html.BeginForm("Cars", "Expense", FormMethod.Post, 
          new { enctype = "multipart/form-data" }))
{ 

    @Html.LabelFor(m => m.Description)
    <div>@Html.TextBoxFor(m => m.Description)</div>

    @Html.LabelFor(m => m.Amount)
    <div>@Html.TextBoxFor(m => m.Amount)</div>
    <input type="file" name="FileUpload1"  />
    <input type="file" name="FileUpload2"  />
    <input type="file" name="FileUpload3"  />
    <input type="file" name="FileUpload4"  />
    <input type="file" name="FileUpload5"  />

    <input type="submit" value="Upload" class="btn" />

    <div class="err">
        @Html.ValidationSummary()
    </div>
}

Finally without any further description here is our CarsController, which is the simplest one, see

[HttpGet]
public ActionResult Expense()
{
    return View();
}

[HttpPost]
public ActionResult Expense(ExpenseModel model)
{
    /* Code to save save model data into database. */ 

     foreach (string upload in Request.Files)
     {
         if (Request.Files[upload].ContentLength == 0) continue;
         string pathToSave = Server.MapPath ("~/Documents/");
         string filename = Path.GetFileName(Request.Files[upload].FileName);
         Request.Files[upload].SaveAs(Path.Combine(pathToSave, filename));
      }
      return View();
 }

In our post action we are not getting any file or list of files as a parameter. Yes, we don't need that, we can get a collection of files by using Request.Files as I am looping it and try to check the length of posted file if length is zero, try to check next control.

In this article I added 5 input type="file", but we can add a button to add controls dynamically by using JavaScript. In this way we can give facility to add as much control as user wants. So we can give option to add or remove control.

For a better approach see the linkTo upload image with client side validation and image type all is set in model itself

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • mvc
  • file-upload
By Ali Adravi On 04 Jun, 13  Viewed: 19,140

Other blogs you may like

mvc search page example with code

MVC Searh page with pagination: It’s very easy to create a search page in asp.net but when I try to create the same in MVC I faced many problems, how to create model, how to keep searched values in search controls, pagination, I found myself nowhere, so start searching for some good examples but... By Ali Adravi   On 25 Aug 2013  Viewed: 28,312

MVC insert update delete and select records

CRUD (Create, Retrieve, Update and Delete) in MVC. When we start to learn new language, first we try to run an application with “Hello World” and then CRUD functionality. So in this article we will see how to select records from database (with WebGrid, pagination and sort functionality), update a... By Ali Adravi   On 17 Aug 2013  Viewed: 82,195

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account functionality in our application then we need a thanks page after registering with our site, to say thanks for registering with us or showing confirmation that your password is successfully changed or... By Hamden   On 30 Jun 2013  Viewed: 2,548

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 4,863

ASP.Net MVC file upload

How to upload file or image in asp.net mvc is not difficult but is totally different compare to asp.net FileUpload control. If we are asp.net developer and we are new to mvc then we immediately noticed we don’t have server side controls so the FileUpload control as well and our problem start here.... By Ali Adravi   On 25 May 2013  Viewed: 6,326