Uploading, Validating, And Storing A File Into Database Using EF In ASP.NET MVC5

Introduction
 
Many times, we want to upload a file with a strongly-typed View and also, apply the validation on uploading a file, using jQuery. In this article, I would like to share how to upload a file and validate that file first at client-side and then at the server-side. Once the validation is done, it will post the model data with a file to the Controller to save in a file and also in the database. Now, let's move forward.
 
Prerequisites  
  • Visual Studio
  • SQL Server
  • Basic Knowledge of ASP.Net MVC 
  • Basic Knowledge of Entity Framework
  • Basic Knowledge of JQuery 
  • Basic Knowledge of T-SQL
Article Flow 
  • Create a table in database
  • Create ASP.NET MVC Empty project
  • Create a Model
  • Configure Entity Framework with database and application 
  • Create a Controller with Data Save Logics
  • Create a strongly-typed View
  • jQuery Validation
  • Run an application
  • View database table  
Create a table in the database
 
I have created a table "Candidates" with the following design. 
 
 
 
To create this Candidates table, execute the below query. 
  1. CREATE TABLE [dbo].[Candidates](  
  2. [ID] [int] IDENTITY(1,1) NOT NULL,  
  3. [FirstName] [nvarchar](200) NULL,  
  4. [LastName] [nvarchar](200) NULL,  
  5. [Skills] [nvarchar](maxNULL,  
  6. [EmailID] [nvarchar](200) NULL,  
  7. [ContactNo] [nvarchar](20) NULL,  
  8. [Position] [nvarchar](200) NULL,  
  9. [Resume] [nvarchar](300) NULL,  
  10. [CreatedOn] [datetime] NULL,  
  11. CONSTRAINT [PK_Candidates] PRIMARY KEY CLUSTERED  
  12. (  
  13. [ID] ASC  
  14. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  15. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  16. GO  
Create ASP.NET MVC 5 empty project 
  • Select New Project -> Visual C# -> Web -> ASP.NET Web Application and enter your application name. Here, I named it "FileUploadControlINMVC".
  • Now, click OK.
  • Then, select Empty Web API template and click OK to create the project. 
  • Once you click OK, the project will be created with the basic architecture of MVC.
  • If you are not aware of how to create an Empty ASP.NET Web Application, please visit Step1 and Step 2 to learn.
Create a Model
 
Now, create a Model to create a strongly-typed View. Here, I have created a Model with the name "Employee" as below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace FileUploadControlINMVC.Models {  
  6.     public class Employee {  
  7.         public int Id {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string FirstName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string LastName {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string Skills {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string EmailID {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         public string ContactNo {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         public string Position {  
  32.             get;  
  33.             set;  
  34.         }  
  35.         public HttpPostedFileBase Resume {  
  36.             get;  
  37.             set;  
  38.         }  
  39.     }  
  40. }  
Configure Entity Framework with Database and Application
 
Here(Implement "Database First" approach with Entity Framework), I have already discussed how to configure and implement the database-first approach. In the meantime, choose your created table with Entity Framework. Once we are done with our configuration with SQL table "Candidates" from CRUD database, we will get the below screen as a succeeding configuration.

 
 
Create a Controller with Data Save Logics
 
Now, create an empty Controller under Controllers folder with the name of "FileUploadController". Whenever we create an empty Controller, it will create a Get Action method in the name of Index. Here, we will create as Upload and write the logic to save the candidate data into a database. Save the uploaded file to the physical server folder.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using FileUploadControlINMVC.Models;  
  7. using System.IO;  
  8. namespace FileUploadControlINMVC.Controllers {  
  9.     public class FileUploadController: Controller {  
  10.         //  
  11.         // GET: /FileUpload/  
  12.         [HttpGet]  
  13.         public ActionResult Upload() {  
  14.                 return View();  
  15.             }  
  16.             [HttpPost]  
  17.         public ActionResult Upload(Employee employee) {  
  18.             using(CSharpCornerEntities1 entity = new CSharpCornerEntities1()) {  
  19.                 var candidate = new Candidate() {  
  20.                     ContactNo = employee.ContactNo,  
  21.                         EmailID = employee.EmailID,  
  22.                         FirstName = employee.FirstName,  
  23.                         LastName = employee.LastName,  
  24.                         Position = employee.Position,  
  25.                         Resume = SaveToPhysicalLocation(employee.Resume),  
  26.                         Skills = employee.Skills,  
  27.                         CreatedOn = DateTime.Now  
  28.                 };  
  29.                 entity.Candidates.Add(candidate);  
  30.                 entity.SaveChanges();  
  31.             }  
  32.             return View(employee);  
  33.         }  
  34.         /// <summary>  
  35.         /// Save Posted File in Physical path and return saved path to store in a database  
  36.         /// </summary>  
  37.         /// <param name="file"></param>  
  38.         /// <returns></returns>  
  39.         private string SaveToPhysicalLocation(HttpPostedFileBase file) {  
  40.             if (file.ContentLength > 0) {  
  41.                 var fileName = Path.GetFileName(file.FileName);  
  42.                 var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);  
  43.                 file.SaveAs(path);  
  44.                 return path;  
  45.             }  
  46.             return string.Empty;  
  47.         }  
  48.     }  
  49. }  
Detailed Description 
  • CSharpCornerEntities1 -> It's a Entity Framework Context Name
  • Upload-> It’s the post action method that this View will post, and to which, it saves the file into a database
  • SaveToPhysicalLocation -> This is the action method that this view will post to which saves the file into a directory in the App_Data folder.
Create a strongly-typed View
 
Before creating a strongly-typed View, we should know what strongly-typed View is, right? The strongly-typed View represents "The View which binds to with any Model is called as a strongly-typed View. You can bind any class as a Model to the View.You can access Model properties in that View. You can use data associated with a Model to render the controls".
 
Okay! Now, create a strongly-typed View by right-clicking on Upload. You get the action method, just select Add View. Once you click "Add View", it will show the below screen. On the below screen, select Employee Model to create a strongly-typed View.
 
 

Or create an empty View and add the below code to it to convert that respective View as strongly-typed View. In the meantime, select appropriate Model to get or post the data. 
  1. @model FileUploadControlINMVC.Models.Employee    
Now, design the View like Job Application with the below controls.
  1. <body>  
  2.     <div> @using (Html.BeginForm("Upload""FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" })) { <br />  
  3.         <table cellpadding="5">  
  4.             <thead>  
  5.                 <tr>  
  6.                     <td colspan="2" style="text-align:center">Sr. DotNet Developer</td>  
  7.                 </tr>  
  8.             </thead>  
  9.             <tr>  
  10.                 <td colspan="2"> Please fill <span style="color:red">(*)</span> out below fields and click Apply for this position </td>  
  11.             </tr>  
  12.             <tr>  
  13.                 <td> @Html.LabelFor(m => m.FirstName)<b style="color:red"> *</b> </td>  
  14.                 <td> @Html.TextBoxFor(m => m.FirstName, new { maxlength = 25 }) </td>  
  15.             </tr>  
  16.             <tr>  
  17.                 <td> @Html.LabelFor(m => m.LastName)<b style="color:red"> *</b> </td>  
  18.                 <td> @Html.TextBoxFor(m => m.LastName) </td>  
  19.             </tr>  
  20.             <tr>  
  21.                 <td> @Html.LabelFor(m => m.Position)<b style="color:red"> *</b> </td>  
  22.                 <td> @Html.TextBoxFor(m => m.Position, new { @Value = "Sr. DotNet Developer", @readonly = "readonly" }) </td>  
  23.             </tr>  
  24.             <tr>  
  25.                 <td> @Html.LabelFor(m => m.Skills)<b style="color:red"> *</b> </td>  
  26.                 <td> @Html.TextBoxFor(m => m.Skills) </td>  
  27.             </tr>  
  28.             <tr>  
  29.                 <td> @Html.LabelFor(m => m.EmailID)<b style="color:red"> *</b> </td>  
  30.                 <td> @Html.TextBoxFor(m => m.EmailID, new { type = "email" }) </td>  
  31.             </tr>  
  32.             <tr>  
  33.                 <td> @Html.LabelFor(m => m.ContactNo)<b style="color:red"> *</b> </td>  
  34.                 <td> @Html.TextBoxFor(m => m.ContactNo, new { @type = "number" }) </td>  
  35.             </tr>  
  36.             <tr>  
  37.                 <td> @Html.LabelFor(m => m.Resume)<b style="color:red"> *</b> </td>  
  38.                 <td> @Html.TextBoxFor(m => m.Resume, new { type = "file" }) </td>  
  39.             </tr>  
  40.             <tr>  
  41.                 <td colspan="2" style="text-align:right"> <input type="submit" id="Apply" value="Apply" /> </td>  
  42.             </tr>  
  43.         </table> } </div>  
  44. </body>  
Detailed Description
  1. @using (Html.BeginForm("Upload""FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))  
The above code represents which Controller and action should be called on the form post. Here, we mentioned to FileUpload Controller and Upload action method. The FormMethod.Post parameter enables this to do the post-operation, and new { enctype = "multipart/form-data" } to allow the user to post the file(s) to the Controller with strongly-typed View.
 
Then, I created strongly-typed Textbox control for Firstname, Lastname, Position as read-only with static data, Skills, EmailID with Email Type, ContactNo with Number type and Resume with a file type. You can see these all in the above code and everything is textbox and we changed the type depending on it.
 
Now, add a CSS to this table to give a rich look.
  1. <style>  
  2.     table,  
  3.     th,  
  4.     td {  
  5.         border: 1px solid black;  
  6.         padding: 15px;  
  7.     }  
  8.   
  9.     thead {  
  10.         background-color: skyblue;  
  11.         color: white;  
  12.     }  
  13. </style>  
jQuery Validation
 
Now, we need to validate if the user entered all the required fields. So, add the below code to validate on Apply (Submit) button; click it and check whether you referred the jQuery from the head section or shared layout pages.
  1. <script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")" type="text/javascript"></script>   
  2.    
  3. $("#Apply").click(function () {  
  4. if ($("#FirstName").val() = null || $("#LastName").val() || $("#Skills").val() || $("#EmailID").val() || $("#ContactNo").val() || $("#Resume").val())  
  5.    {  
  6.       alert("Please fill out required fields(*)");  
  7.       return false;  
  8.    }  
  9.    return true;  
  10. });  
And now, we should restrict the user to upload the resume in some listed formats only with the limit of file size.Okay, let's add the below code into head section.
  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         $('#Apply').prop('disabled'true);  
  4.         $("#Resume").change(function() {  
  5.             // Get uploaded file extension  
  6.             var extension = $(this).val().split('.').pop().toLowerCase();  
  7.             // Create array with the files extensions that we wish to upload  
  8.             var validFileExtensions = ['doc''docx''pdf'];  
  9.             //Check file extension in the array.if -1 that means the file extension is not in the list.  
  10.             if ($.inArray(extension, validFileExtensions) == -1) {  
  11.                 alert("Sorry!! Upload only 'doc', 'docx', 'pdf' file")  
  12.                 // Clear fileuload control selected file  
  13.                 $(this).replaceWith($(this).val('').clone(true));  
  14.                 //Disable Submit Button  
  15.                 $('#Apply').prop('disabled'true);  
  16.             } else {  
  17.                 // Check and restrict the file size to 128 KB.  
  18.                 if ($(this).get(0).files[0].size > (131072)) {  
  19.                     alert("Sorry!! Max allowed file size is 128 kb");  
  20.                     // Clear fileuload control selected file  
  21.                     $(this).replaceWith($(this).val('').clone(true));  
  22.                     //Disable Submit Button  
  23.                     $('#Apply').prop('disabled'true);  
  24.                 } else {  
  25.                     //Enable Submit Button  
  26.                     $('#Apply').prop('disabled'false);  
  27.                 }  
  28.             }  
  29.         });  
  30.         $("#Apply").click(function() {  
  31.             if ($("#FirstName").val() = null || $("#LastName").val() || $("#Skills").val() || $("#EmailID").val() || $("#ContactNo").val() || $("#Resume").val()) {  
  32.                 alert("Please fill out required fields(*)");  
  33.                 return false;  
  34.             }  
  35.             return true;  
  36.         });  
  37.     });  
  38. </script>  
In the above code, you can see that we allowed the user to upload only .doc, .docx, and pdf files and the file size should be within 128 kb.
 
Detailed Description 
  1. $("#Resume").change(function () { -> Upload Control change Event  
  2. $('#Apply').prop('disabled'true); -> "Apply button should be disabled untill user fills the required data".  
  3. var extension = $(this).val().split('.').pop().toLowerCase(); -> Get uploaded file extension  
  4. var validFileExtensions = ['doc''docx''pdf']; -> Create array with the files extensions that we wish to upload  
  5. if ($.inArray(extension, validFileExtensions) == -1) {-> //Check file extension in the array.if -1 that means the file extension is not in the list.  
  6. $(this).replaceWith($(this).val('').clone(true)); -> Clear fileuload control selected file  
  7. if ($(this).get(0).files[0].size > (131072)) { ->Check and restrict the file size to 128 KB.  
  8. $('#Apply').prop('disabled'false);->  //Enable Apply Button   
Now, run your application.
 
 
 
Now, fill out the form fields, try uploading different file formats. Here, I am trying to upload the image file. Let's see if our jQuery is working or not.
 
 

In the below image, you can see that the file type has been validated.
 
 
 
 Now, let us check the file size limit.
 
 
In the below image, you can see that the file size has been validated.
 
 

After successful validation, the value data will be posted to the Controller.

 
 
The file has been stored in a physical location. Here, we mentioned storing in the App_Data folder.
 
 
 
The candidate record has been created in the database as below.
 
 
Complete View 
  1. @model FileUploadControlINMVC.Models.Employee  
  2. @{  
  3.    ViewBag.Title = "Upload";  
  4.    Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6. <!DOCTYPE html>  
  7. <html>  
  8.   
  9. <head>  
  10.     <meta name="viewport" content="width=device-width" />  
  11.     <title>Index</title>  
  12.     <script src="@Url.Content(" ~/Scripts/jquery-1.10.2.min.js ")" type="text/javascript"></script>  
  13.     <script type="text/javascript">  
  14.         $(document).ready(function() {  
  15.             $('#Apply').prop('disabled'true);  
  16.             $("#Resume").change(function() {  
  17.                 // Get uploaded file extension  
  18.                 var extension = $(this).val().split('.').pop().toLowerCase();  
  19.                 // Create array with the files extensions that we wish to upload  
  20.                 var validFileExtensions = ['doc''docx''pdf'];  
  21.                 //Check file extension in the array.if -1 that means the file extension is not in the list.  
  22.                 if ($.inArray(extension, validFileExtensions) == -1) {  
  23.                     alert("Sorry!! Upload only 'doc', 'docx', 'pdf' file")  
  24.                     // Clear fileuload control selected file  
  25.                     $(this).replaceWith($(this).val('').clone(true));  
  26.                     //Disable Submit Button  
  27.                     $('#Apply').prop('disabled'true);  
  28.                 } else {  
  29.                     // Check and restrict the file size to 128 KB.  
  30.                     if ($(this).get(0).files[0].size > (131072)) {  
  31.                         alert("Sorry!! Max allowed file size is 128 kb");  
  32.                         // Clear fileuload control selected file  
  33.                         $(this).replaceWith($(this).val('').clone(true));  
  34.                         //Disable Submit Button  
  35.                         $('#Apply').prop('disabled'true);  
  36.                     } else {  
  37.                         //Enable Submit Button  
  38.                         $('#Apply').prop('disabled'false);  
  39.                     }  
  40.                 }  
  41.             });  
  42.             $("#Apply").click(function() {  
  43.                 if ($("#FirstName").val() = null || $("#LastName").val() || $("#Skills").val() || $("#EmailID").val() || $("#ContactNo").val() || $("#Resume").val()) {  
  44.                     alert("Please fill out required fields(*)");  
  45.                     return false;  
  46.                 }  
  47.                 return true;  
  48.             });  
  49.         });  
  50.     </script>  
  51.     <style>  
  52.         table,  
  53.         th,  
  54.         td {  
  55.             border: 1px solid black;  
  56.             padding: 15px;  
  57.         }  
  58.   
  59.         thead {  
  60.             background-color: skyblue;  
  61.             color: white;  
  62.         }  
  63.     </style>  
  64. </head>  
  65.   
  66. <body>  
  67.     <div> @using (Html.BeginForm("Upload""FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" })) { <br />  
  68.         <table cellpadding="5">  
  69.             <thead>  
  70.                 <tr>  
  71.                     <td colspan="2" style="text-align:center">Sr. DotNet Developer</td>  
  72.                 </tr>  
  73.             </thead>  
  74.             <tr>  
  75.                 <td colspan="2"> Please fill <span style="color:red">(*)</span> out below fields and click Apply for this position </td>  
  76.             </tr>  
  77.             <tr>  
  78.                 <td> @Html.LabelFor(m => m.FirstName)<b style="color:red"> *</b> </td>  
  79.                 <td> @Html.TextBoxFor(m => m.FirstName, new { maxlength = 25 }) </td>  
  80.             </tr>  
  81.             <tr>  
  82.                 <td> @Html.LabelFor(m => m.LastName)<b style="color:red"> *</b> </td>  
  83.                 <td> @Html.TextBoxFor(m => m.LastName) </td>  
  84.             </tr>  
  85.             <tr>  
  86.                 <td> @Html.LabelFor(m => m.Position)<b style="color:red"> *</b> </td>  
  87.                 <td> @Html.TextBoxFor(m => m.Position, new { @Value = "Sr. DotNet Developer", @readonly = "readonly" }) </td>  
  88.             </tr>  
  89.             <tr>  
  90.                 <td> @Html.LabelFor(m => m.Skills)<b style="color:red"> *</b> </td>  
  91.                 <td> @Html.TextBoxFor(m => m.Skills) </td>  
  92.             </tr>  
  93.             <tr>  
  94.                 <td> @Html.LabelFor(m => m.EmailID)<b style="color:red"> *</b> </td>  
  95.                 <td> @Html.TextBoxFor(m => m.EmailID, new { type = "email" }) </td>  
  96.             </tr>  
  97.             <tr>  
  98.                 <td> @Html.LabelFor(m => m.ContactNo)<b style="color:red"> *</b> </td>  
  99.                 <td> @Html.TextBoxFor(m => m.ContactNo, new { @type = "number" }) </td>  
  100.             </tr>  
  101.             <tr>  
  102.                 <td> @Html.LabelFor(m => m.Resume)<b style="color:red"> *</b> </td>  
  103.                 <td> @Html.TextBoxFor(m => m.Resume, new { type = "file" }) </td>  
  104.             </tr>  
  105.             <tr>  
  106.                 <td colspan="2" style="text-align:right"> <input type="submit" id="Apply" value="Apply" /> </td>  
  107.             </tr>  
  108.         </table> } </div>  
  109. </body>  
  110.   
  111. </html>  
Complete Controller
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using FileUploadControlINMVC.Models;  
  7. using System.IO;  
  8. namespace FileUploadControlINMVC.Controllers {  
  9.     public class FileUploadController: Controller {  
  10.         //  
  11.         // GET: /FileUpload/  
  12.         [HttpGet]  
  13.         public ActionResult Upload() {  
  14.                 return View();  
  15.             }  
  16.             [HttpPost]  
  17.         public ActionResult Upload(Employee employee) {  
  18.             using(CSharpCornerEntities1 entity = new CSharpCornerEntities1()) {  
  19.                 var candidate = new Candidate() {  
  20.                     ContactNo = employee.ContactNo,  
  21.                         EmailID = employee.EmailID,  
  22.                         FirstName = employee.FirstName,  
  23.                         LastName = employee.LastName,  
  24.                         Position = employee.Position,  
  25.                         Resume = SaveToPhysicalLocation(employee.Resume),  
  26.                         Skills = employee.Skills,  
  27.                         CreatedOn = DateTime.Now  
  28.                 };  
  29.                 entity.Candidates.Add(candidate);  
  30.                 entity.SaveChanges();  
  31.             }  
  32.             return View(employee);  
  33.         }  
  34.         /// <summary>  
  35.         /// Save Posted File in Physical path and return saved path to store in a database  
  36.         /// </summary>  
  37.         /// <param name="file"></param>  
  38.         /// <returns></returns>  
  39.         private string SaveToPhysicalLocation(HttpPostedFileBase file) {  
  40.             if (file.ContentLength > 0) {  
  41.                 var fileName = Path.GetFileName(file.FileName);  
  42.                 var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);  
  43.                 file.SaveAs(path);  
  44.                 return path;  
  45.             }  
  46.             return string.Empty;  
  47.         }  
  48.     }  
  49. }  
Model (Employee.cs)
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace FileUploadControlINMVC.Models {  
  6.     public class Employee {  
  7.         public int Id {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string FirstName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string LastName {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string Skills {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string EmailID {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         public string ContactNo {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         public string Position {  
  32.             get;  
  33.             set;  
  34.         }  
  35.         public HttpPostedFileBase Resume {  
  36.             get;  
  37.             set;  
  38.         }  
  39.     }  
  40. }  
Please find the attached project for your reference. I did attach the demo project without package for Entity Framework 6.0 due to file size exceeded 25MB.
 
Summary 
 
In this article, we learned how to work with strongly-typed View to upload a file, validate the file, and store it to a physical path as well as a database table. I hope it's helpful.
 
Your valuable feedback and comments about this article are always welcome.