Javascript required
Skip to content Skip to sidebar Skip to footer

Step by Step in File Upload Mvc

Implementation Summary

  1. Create a "tblMembers" tabular array 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 tape into a database tabular array.

Step past step Implementation

ASP.NET

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

  1. Proper noun Textbox
  2. Phone Number Textbox
  3. Image File Upload
  4. Submit Push

Create a "tblMembers" table in the database.

  1. Use [MbkTest]
  2. Go
  3. Gear up  ANSI_NULLS ON
  4. GO
  5. Fix  QUOTED_IDENTIFIER ON
  6. Become
  7. SET  ANSI_PADDING ON
  8. GO
  9. CREATE Table  [dbo].[tblMembers](
  10.     [MemberID] [int ] IDENTITY(1,1) Not Zippo ,
  11.     [MemberName] [varchar ](50) Naught ,
  12.     [PhoneNumber] [varchar ](50) NULL ,
  13.     [ImagePath] [varchar ](500) Cypher ,
  14. PRIMARY Key  Amassed
  15. (
  16.     [MemberID]ASC
  17. )WITH  (PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON  [ PRIMARY ]
  18. )ON  [ Primary ]
  19. GO
  20. SET  ANSI_PADDING OFF
  21. Go

Create a new ASP.NET MVC project called "ClubMember".

ASP.NET

Click on "Alter Hallmark".

ASP.NET

But we are looking for the following output.

ASP.NET

Click on "Change Authentication" push and select No Hallmark.

ASP.NET

ASP.NET

We take created a project called "ClubMember". Now, nosotros are going to add together "MemberModel".

Correct-click on "MODELS" folder or press CTRL+SHIFT+A to add new Model (Course).

ASP.NET

Give Model Name: "MemberModel".

ASP.NET

Lawmaking of MemberModel.cs

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

At present, build your project by correct-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 activeness-method called CONTACTFORM.

ASP.NET

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

ASP.NET

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

ASP.NET

As you click on ADD push in VIEWS-->Home folder CONTACTFORM.CSHTML file will exist created.

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

ASP.NET

At present, let usa alter the CSHTML code.

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

ASP.NET

Remove following lawmaking of ImagePath

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

Add together the post-obit lines of code.

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

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

As nosotros take inverse and usedthe HTML File-Upload control named "ImageFile", so now, permit u.s.a. change the model again to modify the titles of fields like this:

  • Name = Fellow member Name
  • PhoneNumber = Telephone / Mobile Number
  • ImagePath = Upload File

Code of MemberModel.cs

  1. using Arrangement;
  2. using System.Collections.Generic;
  3. using Organization.ComponentModel;
  4. using Organisation.ComponentModel.DataAnnotations;
  5. using Organisation.Linq;
  6. using Arrangement.Spider web;
  7. namespace ClubMember.Models
  8. {
  9. public class  MemberModel
  10.     {
  11.         [DisplayName("Member Name" )]
  12. public  string Proper noun { get; set up; }
  13.         [DisplayName("Telephone / Mobile Number" )]
  14. public  string PhoneNumber { get; set; }
  15.         [DisplayName("Upload File" )]
  16. public  string ImagePath { get; set; }
  17. public  HttpPostedFileBase ImageFile { get; set; }
  18.     }
  19. }

Note
DisplayName attribute comes later on using the following namespaces.

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

Now, again, switch to CONTACTFORM.CSHTML file, practice the following changes and printing F5.

ASP.NET

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

Line No. 10

@using (Html.BeginForm())

Alter this to:

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

Now, allow u.s.a. switch dorsum to the controller to work on it.

ASP.NET

ASP.NET

  1. [HttpPost]
  2. public  ActionResult ContactForm(MemberModel membervalues)
  3. {
  4.     cord FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);
  5.     string FileExtension = Path.GetExtension(membervalues.ImageFile.FileName);
  6.     FileName = DateTime.Now.ToString("yyyyMMdd" )+ "-" +FileName.Trim()+ FileExtension;
  7.     cord UploadPath = ConfigurationManager.AppSettings["UserImagePath" ].ToString();
  8.     membervalues.ImagePath = UploadPath + FileName;
  9.     membervalues.ImageFile.SaveAs(membervalues.ImagePath);
  10. render  View();
  11. }

Afterwards updating the HTTPPOST code, at present, it is time to create a new folder called "UserImages".

ASP.NET

You lot tin run across in the Solution Explorer binder 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 central="webpages:Version"  value= "3.0.0.0"  />
  4.     <add together key="webpages:Enabled"  value= "imitation"  />
  5.     <add fundamental="ClientValidationEnabled"  value= "true"  />
  6.     <add key="UnobtrusiveJavaScriptEnabled"  value= "true"  />
  7.     <add together central="UserImagePath"  value= "D:\MBK\ClubMember\ClubMember\UserImages\"  />
  8.   </appSettings>

In the above lawmaking, y'all can see UserImagePath key created with the value.

Now, fill up the course.

ASP.NET

Later clicking on CREATE button and submitting the grade, you can meet your selected file copied in the set folder in web.config.

ASP.NET

At present, nosotros 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 projection name "ClubMember".

ASP.NET

Select Data--->LINQ to SQL Classes. Give proper name "ClubMemberDataClasses.dbml".

ASP.NET

Open ClubMemberDataClasses.dbml file and open Server Explorer.

ASP.NET

Click on the red push that is "Connect to database". As y'all click on this button, yous volition get the following dialog box.

ASP.NET

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

Now, yous tin can run into database is opened in Server Explorer.

ASP.NET

Now, elevate and drop tblMembers inside ClubMemberDataClasses.dbml.

ASP.NET

At present, 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 Arrangement;
  3. using Arrangement.Collections.Generic;
  4. using System.IO;
  5. using Arrangement.Linq;
  6. using System.Web;
  7. using Organization.Web.Mvc;
  8. using Organization.Configuration;
  9. namespace ClubMember.Controllers
  10. {
  11. public class  HomeController : Controller
  12.     {
  13. public  ActionResult Index()
  14.         {
  15. return  View();
  16.         }
  17. public  ActionResult Near()
  18.         {
  19.             ViewBag.Bulletin ="Your application description page." ;
  20. return  View();
  21.         }
  22. public  ActionResult Contact()
  23.         {
  24.             ViewBag.Bulletin ="Your contact folio." ;
  25. return  View();
  26.         }
  27.         [HttpGet]
  28. public  ActionResult ContactForm()
  29.         {
  30. return  View();
  31.         }
  32.         [HttpPost]
  33. public  ActionResult ContactForm(MemberModel membervalues)
  34.         {
  35.             string FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);
  36.             string FileExtension = Path.GetExtension(membervalues.ImageFile.FileName);
  37.             FileName = DateTime.Now.ToString("yyyyMMdd" )+ "-" +FileName.Trim()+ FileExtension;
  38.             cord UploadPath = ConfigurationManager.AppSettings["UserImagePath" ].ToString();
  39.             membervalues.ImagePath = UploadPath + FileName;
  40.             membervalues.ImageFile.SaveAs(membervalues.ImagePath);
  41. var  db = new  ClubMemberDataClassesDataContext();
  42.             tblMember _member =new  tblMember();
  43.             _member.ImagePath = membervalues.ImagePath;
  44.             _member.MemberName = membervalues.Name;
  45.             _member.PhoneNumber = membervalues.PhoneNumber;
  46.             db.tblMembers.InsertOnSubmit(_member);
  47.             db.SubmitChanges();
  48. return  View();
  49.         }
  50.     }
  51. }

Code ContactForm.cshtml

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

Code MemberModel.cs

  1. using System;
  2. using Organisation.Collections.Generic;
  3. using Organisation.ComponentModel;
  4. using Organisation.ComponentModel.DataAnnotations;
  5. using System.Linq;
  6. using System.Web;
  7. namespace ClubMember.Models
  8. {
  9. public class  MemberModel
  10.     {
  11.         [DisplayName("Member Proper name" )]
  12. public  string Proper name { get; set; }
  13.         [DisplayName("Telephone / Mobile Number" )]
  14. public  string PhoneNumber { get; set; }
  15.         [DisplayName("Upload File" )]
  16. public  string ImagePath { go; set; }
  17. public  HttpPostedFileBase ImageFile { get; set; }
  18.     }
  19. }

ASP.NET

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

Look here. The above tape is inserted successfully.

ASP.NET

Thank yous .

Happy Coding.

bettsskeethe.blogspot.com

Source: https://www.c-sharpcorner.com/article/asp-net-mvc-form-with-file-upload/