ASP.NET MVC Form With File Upload

Implementation Summary 

  1. Create a “tblMembers” table in your Database.
  2. Create a new ASP.NET MVC web application project called “ClubMember”.
  3. Create a Model called “MemberModel”.
  4. Create HTTPGET ActionMethod called “ContactForm”.
  5. Create a view of “ContactForm”.
  6. Use HTML File Upload control.
  7. Create HTTPPOST ActionMethod called “ContactForm” to insert record in table and save file in Server.
  8. Add Linq To Sql class “ClubMember”.
  9. Insert a record into a database table.

Step by step Implementation

ASP.NET

 

In the above form, you can see there are four objects. 

  1. Name Textbox
  2. Phone Number Textbox
  3. Image File Upload
  4. Submit Button

Create a “tblMembers” table in the database.

  1. USE [MbkTest]  
  2. GO  
  3.   
  4. SET ANSI_NULLS ON  
  5. GO  
  6.   
  7. SET QUOTED_IDENTIFIER ON  
  8. GO  
  9.   
  10. SET ANSI_PADDING ON  
  11. GO  
  12.   
  13. CREATE TABLE [dbo].[tblMembers](  
  14.     [MemberID] [int] IDENTITY(1,1) NOT NULL,  
  15.     [MemberName] [varchar](50) NULL,  
  16.     [PhoneNumber] [varchar](50) NULL,  
  17.     [ImagePath] [varchar](500) NULL,  
  18. PRIMARY KEY CLUSTERED   
  19. (  
  20.     [MemberID] ASC  
  21. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  22. ON [PRIMARY]  
  23.   
  24. GO  
  25. SET ANSI_PADDING OFF  
  26.   
  27. GO  

Create a new ASP.NET MVC project called “ClubMember”.

ASP.NET

Click on “Change Authentication”.

ASP.NET

But we are looking for the following output.

ASP.NET

Click on “Change Authentication” button and select No Authentication.

ASP.NET
 
ASP.NET

We have created a project called “ClubMember“. Now, we are going to add “MemberModel”.

Right-click on “MODELS” folder or press CTRL+SHIFT+A to add new Model (CLASS).

ASP.NET

Give Model Name: “MemberModel”.

ASP.NET

Code of MemberModel.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace ClubMember.Models  
  7. {  
  8.     public class MemberModel  
  9.     {  
  10.         public string Name { get; set; }  
  11.         public string PhoneNumber { get; set; }  
  12.         public string ImagePath { get; set; }  
  13.         public HttpPostedFile ImageFile { get; set; }  
  14.     }  
  15. }  

Now, build your project by right-clicking on the project and selecting BUILD.

ASP.NET

Now, switch to HOME Controller. Click on Controllers folder and double click on HOMECONTROLLER.CS file.

Create an action-method called CONTACTFORM.

ASP.NET

By default, the Add View dialog box will display as below.

ASP.NET

Fill the "ADD VIEW" dialog box with the following values.

ASP.NET

As you click on ADD button in VIEWS-->HOME folder CONTACTFORM.CSHTML file will be created.

Switch to CONTACTFORM.CSHTML file and press F5. The output screen is given below.

ASP.NET

Now, let us modify the CSHTML code.

Switch to CONTACTFORM.CSHTML file,  do the following changes and press F5.

ASP.NET

Remove following code of ImagePath

  1. @Html.EditorFor(model => model.ImagePath, new { htmlAttributes = new { @class = "form-control" } })  
  2. @Html.ValidationMessageFor(model => model.ImagePath, ""new { @class = "text-danger" })  

Add the following lines of code.

  1. <input type="file" name="ImageFile" required />  

The above code line is the HTML control for file uploading.

As we have changed and usedthe HTML File-Upload control named ”ImageFile”, so now, let us change the model again to change the titles of fields like this: 

  • Name = Member Name
  • PhoneNumber = Telephone / Mobile Number
  • ImagePath = Upload File

Code of MemberModel.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.ComponentModel.DataAnnotations;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace ClubMember.Models  
  9. {  
  10.     public class MemberModel  
  11.     {  
  12.         //To change label title value  
  13.         [DisplayName("Member Name")]  
  14.         public string Name { get; set; }  
  15.   
  16.         //To change label title value  
  17.         [DisplayName("Telephone / Mobile Number")]  
  18.         public string PhoneNumber { get; set; }  
  19.   
  20.         //To change label title value  
  21.         [DisplayName("Upload File")]  
  22.         public string ImagePath { get; set; }  
  23.   
  24.         public HttpPostedFileBase ImageFile { get; set; }  
  25.     }  
  26. }  

Note
DisplayName attribute comes after using the following namespaces.

  1. using System.ComponentModel;  
  2. using System.ComponentModel.DataAnnotations;  

Now, again, switch to CONTACTFORM.CSHTML file, do the following changes and press F5.

ASP.NET

Now, let us switch again to ContactForm.cshtml to change the following.

Line No. 10

@using (Html.BeginForm())

Change this to:

  1. @using(Html.BeginForm("ContactForm""Home", FormMethod.Post, new  
  2. {  
  3.     enctype = "multipart/form-data"  
  4. }))  

Now, let us switch back to the controller to work on it.

ASP.NET
 
ASP.NET 
  1. [HttpPost]  
  2. public ActionResult ContactForm(MemberModel membervalues)  
  3. {  
  4.     //Use Namespace called :  System.IO  
  5.     string FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);  
  6.   
  7.     //To Get File Extension  
  8.     string FileExtension = Path.GetExtension(membervalues.ImageFile.FileName);  
  9.   
  10.     //Add Current Date To Attached File Name  
  11.     FileName = DateTime.Now.ToString("yyyyMMdd")+"-"+FileName.Trim()+ FileExtension;  
  12.   
  13.     //Get Upload path from Web.Config file AppSettings.  
  14.     string UploadPath = ConfigurationManager.AppSettings["UserImagePath"].ToString();  
  15.   
  16.     //Its Create complete path to store in server.  
  17.     membervalues.ImagePath = UploadPath + FileName;  
  18.   
  19.     //To copy and save file into server.  
  20.     membervalues.ImageFile.SaveAs(membervalues.ImagePath);  
  21.   
  22.     return View();  
  23. }  

After updating the HTTPPOST code, now, it is time to create a new folder called “UserImages”.

ASP.NET

You can see in the Solution Explorer folder that the “UserImages”  folder is created.

ASP.NET

Now, open web.config file to add APPSETTING.

AppSetting exists under Configuration Tag.

  1. <configuration>  
  2.   <appSettings>  
  3.     <add key="webpages:Version" value="3.0.0.0" />  
  4.     <add key="webpages:Enabled" value="false" />  
  5.     <add key="ClientValidationEnabled" value="true" />  
  6.     <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
  7.     <add key="UserImagePath" value="D:\MBK\ClubMember\ClubMember\UserImages\" />  
  8.   </appSettings>  

In the above code, you can see UserImagePath key created with the value.

Now, fill the form.

ASP.NET

After clicking on CREATE button and submitting the form, you can see your selected file copied in the set folder in web.config.

ASP.NET

Now, we are going to write the code to store other information of CONTACT FORM details.

  • Member Name
  • Telephone/Mobile Number
  • Image File Path

Right-click on project name “ClubMember”.

ASP.NET

Select Data--->LINQ to SQL Classes. Give name “ClubMemberDataClasses.dbml”.

ASP.NET

Open ClubMemberDataClasses.dbml file and open Server Explorer.

ASP.NET

Click on the red button that is “Connect to database”. As you click on this button, you will get the following dialog box.

ASP.NET

In the above dialog box, you have to provide a Database server name and Authentication level and afterward, select your database.

Now, you can see database is opened in Server Explorer.

ASP.NET

Now, drag and drop tblMembers inside ClubMemberDataClasses.dbml.

ASP.NET

Now, switch back to HomeController to write INSERT record code into database table using LINQ TO SQL.

Code HomeController.cs

  1. using ClubMember.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.Mvc;  
  8. using System.Configuration;  
  9.   
  10. namespace ClubMember.Controllers  
  11. {  
  12.     public class HomeController : Controller  
  13.     {  
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.   
  19.         public ActionResult About()  
  20.         {  
  21.             ViewBag.Message = "Your application description page.";  
  22.   
  23.             return View();  
  24.         }  
  25.   
  26.         public ActionResult Contact()  
  27.         {  
  28.             ViewBag.Message = "Your contact page.";  
  29.   
  30.             return View();  
  31.         }  
  32.   
  33.         [HttpGet]  
  34.         public ActionResult ContactForm()  
  35.         {  
  36.   
  37.             return View();  
  38.         }  
  39.   
  40.         [HttpPost]  
  41.         public ActionResult ContactForm(MemberModel membervalues)  
  42.         {  
  43.             //Use Namespace called :  System.IO  
  44.             string FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);  
  45.   
  46.             //To Get File Extension  
  47.             string FileExtension = Path.GetExtension(membervalues.ImageFile.FileName);  
  48.   
  49.             //Add Current Date To Attached File Name  
  50.             FileName = DateTime.Now.ToString("yyyyMMdd")+"-"+FileName.Trim()+ FileExtension;  
  51.   
  52.             //Get Upload path from Web.Config file AppSettings.  
  53.             string UploadPath = ConfigurationManager.AppSettings["UserImagePath"].ToString();  
  54.   
  55.             //Its Create complete path to store in server.  
  56.             membervalues.ImagePath = UploadPath + FileName;  
  57.   
  58.             //To copy and save file into server.  
  59.             membervalues.ImageFile.SaveAs(membervalues.ImagePath);  
  60.   
  61.   
  62.             //To save Club Member Contact Form Detail to database table.  
  63.             var db =  new ClubMemberDataClassesDataContext();  
  64.   
  65.             tblMember _member = new tblMember();  
  66.   
  67.             _member.ImagePath = membervalues.ImagePath;  
  68.             _member.MemberName = membervalues.Name;  
  69.             _member.PhoneNumber = membervalues.PhoneNumber;  
  70.   
  71.             db.tblMembers.InsertOnSubmit(_member);  
  72.             db.SubmitChanges();  
  73.   
  74.             return View();  
  75.         }  
  76.   
  77.     }  
  78. }  

Code ContactForm.cshtml

  1. @model ClubMember.Models.MemberModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "ContactForm";  
  5. }  
  6.   
  7. <h2>ContactForm</h2>  
  8.   
  9.   
  10. @using (Html.BeginForm("ContactForm","Home",FormMethod.Post,new { enctype="multipart/form-data" }))  
  11. {  
  12.     @Html.AntiForgeryToken()  
  13.       
  14.     <div class="form-horizontal">  
  15.         <h4>MemberModel</h4>  
  16.         <hr />  
  17.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  18.         <div class="form-group">  
  19.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  20.             <div class="col-md-10">  
  21.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  22.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  23.             </div>  
  24.         </div>  
  25.   
  26.         <div class="form-group">  
  27.             @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })  
  28.             <div class="col-md-10">  
  29.                 @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })  
  30.                 @Html.ValidationMessageFor(model => model.PhoneNumber, ""new { @class = "text-danger" })  
  31.             </div>  
  32.         </div>  
  33.   
  34.         <div class="form-group">  
  35.             @Html.LabelFor(model => model.ImagePath, htmlAttributes: new { @class = "control-label col-md-2" })  
  36.             <div class="col-md-10">  
  37.                 <input type="file" name="ImageFile" required />  
  38.             </div>  
  39.         </div>  
  40.   
  41.         <div class="form-group">  
  42.             <div class="col-md-offset-2 col-md-10">  
  43.                 <input type="submit" value="Create" class="btn btn-default" />  
  44.             </div>  
  45.         </div>  
  46.     </div>  
  47. }  
  48.   
  49. <div>  
  50.     @Html.ActionLink("Back to List""Index")  
  51. </div>  
  52.   
  53. @section Scripts {  
  54.     @Scripts.Render("~/bundles/jqueryval")  
  55. }  

Code MemberModel.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.ComponentModel.DataAnnotations;  
  5. using System.Linq;  
  6. using System.Web;  
  7.   
  8. namespace ClubMember.Models  
  9. {  
  10.     public class MemberModel  
  11.     {  
  12.         //To change label title value  
  13.         [DisplayName("Member Name")]  
  14.         public string Name { get; set; }  
  15.   
  16.         //To change label title value  
  17.         [DisplayName("Telephone / Mobile Number")]  
  18.         public string PhoneNumber { get; set; }  
  19.   
  20.         //To change label title value  
  21.         [DisplayName("Upload File")]  
  22.         public string ImagePath { get; set; }  
  23.   
  24.         public HttpPostedFileBase ImageFile { get; set; }  
  25.     }  
  26. }  
ASP.NET

Now, you can check in your SQL Server database table if the record is inserted or not.

Look here. The above record is inserted successfully.

ASP.NET

Thank you .

Happy Coding.


Similar Articles