Now, create a Model to create a strongly-typed View. Here, I have created a Model with the name "Employee" as below.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace FileUploadControlINMVC.Models {
- public class Employee {
- public int Id {
- get;
- set;
- }
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- public string Skills {
- get;
- set;
- }
- public string EmailID {
- get;
- set;
- }
- public string ContactNo {
- get;
- set;
- }
- public string Position {
- get;
- set;
- }
- public HttpPostedFileBase Resume {
- get;
- set;
- }
- }
- }
Configure Entity Framework with Database and Application
Here, 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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using FileUploadControlINMVC.Models;
- using System.IO;
- namespace FileUploadControlINMVC.Controllers {
- public class FileUploadController: Controller {
-
-
- [HttpGet]
- public ActionResult Upload() {
- return View();
- }
- [HttpPost]
- public ActionResult Upload(Employee employee) {
- using(CSharpCornerEntities1 entity = new CSharpCornerEntities1()) {
- var candidate = new Candidate() {
- ContactNo = employee.ContactNo,
- EmailID = employee.EmailID,
- FirstName = employee.FirstName,
- LastName = employee.LastName,
- Position = employee.Position,
- Resume = SaveToPhysicalLocation(employee.Resume),
- Skills = employee.Skills,
- CreatedOn = DateTime.Now
- };
- entity.Candidates.Add(candidate);
- entity.SaveChanges();
- }
- return View(employee);
- }
-
-
-
-
-
- private string SaveToPhysicalLocation(HttpPostedFileBase file) {
- if (file.ContentLength > 0) {
- var fileName = Path.GetFileName(file.FileName);
- var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
- file.SaveAs(path);
- return path;
- }
- return string.Empty;
- }
- }
- }
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.
- @model FileUploadControlINMVC.Models.Employee
Now, design the View like Job Application with the below controls.
- <body>
- <div> @using (Html.BeginForm("Upload", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" })) { <br />
- <table cellpadding="5">
- <thead>
- <tr>
- <td colspan="2" style="text-align:center">Sr. DotNet Developer</td>
- </tr>
- </thead>
- <tr>
- <td colspan="2"> Please fill <span style="color:red">(*)</span> out below fields and click Apply for this position </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.FirstName)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.FirstName, new { maxlength = 25 }) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.LastName)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.LastName) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.Position)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.Position, new { @Value = "Sr. DotNet Developer", @readonly = "readonly" }) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.Skills)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.Skills) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.EmailID)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.EmailID, new { type = "email" }) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.ContactNo)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.ContactNo, new { @type = "number" }) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.Resume)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.Resume, new { type = "file" }) </td>
- </tr>
- <tr>
- <td colspan="2" style="text-align:right"> <input type="submit" id="Apply" value="Apply" /> </td>
- </tr>
- </table> } </div>
- </body>
Detailed Description
- @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.
- <style>
- table,
- th,
- td {
- border: 1px solid black;
- padding: 15px;
- }
-
- thead {
- background-color: skyblue;
- color: white;
- }
- </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.
- <script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")" type="text/javascript"></script>
-
- $("#Apply").click(function () {
- if ($("#FirstName").val() = null || $("#LastName").val() || $("#Skills").val() || $("#EmailID").val() || $("#ContactNo").val() || $("#Resume").val())
- {
- alert("Please fill out required fields(*)");
- return false;
- }
- return true;
- });
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.
- <script type="text/javascript">
- $(document).ready(function() {
- $('#Apply').prop('disabled', true);
- $("#Resume").change(function() {
-
- var extension = $(this).val().split('.').pop().toLowerCase();
-
- var validFileExtensions = ['doc', 'docx', 'pdf'];
-
- if ($.inArray(extension, validFileExtensions) == -1) {
- alert("Sorry!! Upload only 'doc', 'docx', 'pdf' file")
-
- $(this).replaceWith($(this).val('').clone(true));
-
- $('#Apply').prop('disabled', true);
- } else {
-
- if ($(this).get(0).files[0].size > (131072)) {
- alert("Sorry!! Max allowed file size is 128 kb");
-
- $(this).replaceWith($(this).val('').clone(true));
-
- $('#Apply').prop('disabled', true);
- } else {
-
- $('#Apply').prop('disabled', false);
- }
- }
- });
- $("#Apply").click(function() {
- if ($("#FirstName").val() = null || $("#LastName").val() || $("#Skills").val() || $("#EmailID").val() || $("#ContactNo").val() || $("#Resume").val()) {
- alert("Please fill out required fields(*)");
- return false;
- }
- return true;
- });
- });
- </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
- $("#Resume").change(function () { -> Upload Control change Event
- $('#Apply').prop('disabled', true); -> "Apply button should be disabled untill user fills the required data".
- var extension = $(this).val().split('.').pop().toLowerCase(); -> Get uploaded file extension
- var validFileExtensions = ['doc', 'docx', 'pdf']; -> Create array with the files extensions that we wish to upload
- if ($.inArray(extension, validFileExtensions) == -1) {->
- $(this).replaceWith($(this).val('').clone(true)); -> Clear fileuload control selected file
- if ($(this).get(0).files[0].size > (131072)) { ->Check and restrict the file size to 128 KB.
- $('#Apply').prop('disabled', false);->
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
- @model FileUploadControlINMVC.Models.Employee
- @{
- ViewBag.Title = "Upload";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <!DOCTYPE html>
- <html>
-
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- <script src="@Url.Content(" ~/Scripts/jquery-1.10.2.min.js ")" type="text/javascript"></script>
- <script type="text/javascript">
- $(document).ready(function() {
- $('#Apply').prop('disabled', true);
- $("#Resume").change(function() {
-
- var extension = $(this).val().split('.').pop().toLowerCase();
-
- var validFileExtensions = ['doc', 'docx', 'pdf'];
-
- if ($.inArray(extension, validFileExtensions) == -1) {
- alert("Sorry!! Upload only 'doc', 'docx', 'pdf' file")
-
- $(this).replaceWith($(this).val('').clone(true));
-
- $('#Apply').prop('disabled', true);
- } else {
-
- if ($(this).get(0).files[0].size > (131072)) {
- alert("Sorry!! Max allowed file size is 128 kb");
-
- $(this).replaceWith($(this).val('').clone(true));
-
- $('#Apply').prop('disabled', true);
- } else {
-
- $('#Apply').prop('disabled', false);
- }
- }
- });
- $("#Apply").click(function() {
- if ($("#FirstName").val() = null || $("#LastName").val() || $("#Skills").val() || $("#EmailID").val() || $("#ContactNo").val() || $("#Resume").val()) {
- alert("Please fill out required fields(*)");
- return false;
- }
- return true;
- });
- });
- </script>
- <style>
- table,
- th,
- td {
- border: 1px solid black;
- padding: 15px;
- }
-
- thead {
- background-color: skyblue;
- color: white;
- }
- </style>
- </head>
-
- <body>
- <div> @using (Html.BeginForm("Upload", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" })) { <br />
- <table cellpadding="5">
- <thead>
- <tr>
- <td colspan="2" style="text-align:center">Sr. DotNet Developer</td>
- </tr>
- </thead>
- <tr>
- <td colspan="2"> Please fill <span style="color:red">(*)</span> out below fields and click Apply for this position </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.FirstName)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.FirstName, new { maxlength = 25 }) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.LastName)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.LastName) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.Position)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.Position, new { @Value = "Sr. DotNet Developer", @readonly = "readonly" }) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.Skills)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.Skills) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.EmailID)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.EmailID, new { type = "email" }) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.ContactNo)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.ContactNo, new { @type = "number" }) </td>
- </tr>
- <tr>
- <td> @Html.LabelFor(m => m.Resume)<b style="color:red"> *</b> </td>
- <td> @Html.TextBoxFor(m => m.Resume, new { type = "file" }) </td>
- </tr>
- <tr>
- <td colspan="2" style="text-align:right"> <input type="submit" id="Apply" value="Apply" /> </td>
- </tr>
- </table> } </div>
- </body>
-
- </html>
Complete Controller
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using FileUploadControlINMVC.Models;
- using System.IO;
- namespace FileUploadControlINMVC.Controllers {
- public class FileUploadController: Controller {
-
-
- [HttpGet]
- public ActionResult Upload() {
- return View();
- }
- [HttpPost]
- public ActionResult Upload(Employee employee) {
- using(CSharpCornerEntities1 entity = new CSharpCornerEntities1()) {
- var candidate = new Candidate() {
- ContactNo = employee.ContactNo,
- EmailID = employee.EmailID,
- FirstName = employee.FirstName,
- LastName = employee.LastName,
- Position = employee.Position,
- Resume = SaveToPhysicalLocation(employee.Resume),
- Skills = employee.Skills,
- CreatedOn = DateTime.Now
- };
- entity.Candidates.Add(candidate);
- entity.SaveChanges();
- }
- return View(employee);
- }
-
-
-
-
-
- private string SaveToPhysicalLocation(HttpPostedFileBase file) {
- if (file.ContentLength > 0) {
- var fileName = Path.GetFileName(file.FileName);
- var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
- file.SaveAs(path);
- return path;
- }
- return string.Empty;
- }
- }
- }
Model (Employee.cs)
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace FileUploadControlINMVC.Models {
- public class Employee {
- public int Id {
- get;
- set;
- }
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- public string Skills {
- get;
- set;
- }
- public string EmailID {
- get;
- set;
- }
- public string ContactNo {
- get;
- set;
- }
- public string Position {
- get;
- set;
- }
- public HttpPostedFileBase Resume {
- get;
- set;
- }
- }
- }
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.