Step by Step in File Upload Mvc
Implementation Summary
- Create a "tblMembers" tabular array in your Database.
- Create a new ASP.NET MVC web application project called "ClubMember".
- Create a Model called "MemberModel".
- Create HTTPGET ActionMethod called "ContactForm".
- Create a view of "ContactForm".
- Use HTML File Upload control.
- Create HTTPPOST ActionMethod called "ContactForm" to insert record in table and save file in Server.
- Add Linq To Sql class "ClubMember".
- Insert a tape into a database tabular array.
Step past step Implementation
In the above form, you can see there are four objects.
- Proper noun Textbox
- Phone Number Textbox
- Image File Upload
- Submit Push
Create a "tblMembers" table in the database.
- Use [MbkTest]
- Go
- Gear up ANSI_NULLS ON
- GO
- Fix QUOTED_IDENTIFIER ON
- Become
- SET ANSI_PADDING ON
- GO
- CREATE Table [dbo].[tblMembers](
- [MemberID] [int ] IDENTITY(1,1) Not Zippo ,
- [MemberName] [varchar ](50) Naught ,
- [PhoneNumber] [varchar ](50) NULL ,
- [ImagePath] [varchar ](500) Cypher ,
- PRIMARY Key Amassed
- (
- [MemberID]ASC
- )WITH (PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [ PRIMARY ]
- )ON [ Primary ]
- GO
- SET ANSI_PADDING OFF
- Go
Create a new ASP.NET MVC project called "ClubMember".
Click on "Alter Hallmark".
But we are looking for the following output.
Click on "Change Authentication" push and select No Hallmark.
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).
Give Model Name: "MemberModel".
Lawmaking of MemberModel.cs
- using Arrangement;
- using Arrangement.Collections.Generic;
- using Arrangement.Linq;
- using System.Web;
- namespace ClubMember.Models
- {
- public form MemberModel
- {
- public string Proper name { get; set; }
- public string PhoneNumber { get; set; }
- public string ImagePath { get; set; }
- public HttpPostedFile ImageFile { get; ready; }
- }
- }
At present, build your project by correct-clicking on the project and selecting BUILD.
Now, switch to HOME Controller. Click on Controllers folder and double click on HOMECONTROLLER.CS file.
Create an activeness-method called CONTACTFORM.
By default, the Add together View dialog box will display equally below.
Fill the "ADD VIEW" dialog box with the following values.
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.
At present, let usa alter the CSHTML code.
Switch to CONTACTFORM.CSHTML file, exercise the following changes and press F5.
Remove following lawmaking of ImagePath
- @Html.EditorFor(model => model.ImagePath, new { htmlAttributes = new { @ course = "form-control" } })
- @Html.ValidationMessageFor(model => model.ImagePath,"" , new { @ class = "text-danger" })
Add together the post-obit lines of code.
- <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
- using Arrangement;
- using System.Collections.Generic;
- using Organization.ComponentModel;
- using Organisation.ComponentModel.DataAnnotations;
- using Organisation.Linq;
- using Arrangement.Spider web;
- namespace ClubMember.Models
- {
- public class MemberModel
- {
- [DisplayName("Member Name" )]
- public string Proper noun { get; set up; }
- [DisplayName("Telephone / Mobile Number" )]
- public string PhoneNumber { get; set; }
- [DisplayName("Upload File" )]
- public string ImagePath { get; set; }
- public HttpPostedFileBase ImageFile { get; set; }
- }
- }
Note
DisplayName attribute comes later on using the following namespaces.
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
Now, again, switch to CONTACTFORM.CSHTML file, practice the following changes and printing F5.
Now, let us switch once again to ContactForm.cshtml to modify the following.
Line No. 10
@using (Html.BeginForm())
Alter this to:
- @using(Html.BeginForm( "ContactForm" , "Dwelling house" , FormMethod.Post, new
- {
- enctype ="multipart/form-data"
- }))
Now, allow u.s.a. switch dorsum to the controller to work on it.
- [HttpPost]
- public ActionResult ContactForm(MemberModel membervalues)
- {
- cord FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);
- string FileExtension = Path.GetExtension(membervalues.ImageFile.FileName);
- FileName = DateTime.Now.ToString("yyyyMMdd" )+ "-" +FileName.Trim()+ FileExtension;
- cord UploadPath = ConfigurationManager.AppSettings["UserImagePath" ].ToString();
- membervalues.ImagePath = UploadPath + FileName;
- membervalues.ImageFile.SaveAs(membervalues.ImagePath);
- render View();
- }
Afterwards updating the HTTPPOST code, at present, it is time to create a new folder called "UserImages".
You lot tin run across in the Solution Explorer binder that the "UserImages" folder is created.
Now, open web.config file to add APPSETTING.
AppSetting exists under Configuration Tag.
- <configuration>
- <appSettings>
- <add central="webpages:Version" value= "3.0.0.0" />
- <add together key="webpages:Enabled" value= "imitation" />
- <add fundamental="ClientValidationEnabled" value= "true" />
- <add key="UnobtrusiveJavaScriptEnabled" value= "true" />
- <add together central="UserImagePath" value= "D:\MBK\ClubMember\ClubMember\UserImages\" />
- </appSettings>
In the above lawmaking, y'all can see UserImagePath key created with the value.
Now, fill up the course.
Later clicking on CREATE button and submitting the grade, you can meet your selected file copied in the set folder in web.config.
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".
Select Data--->LINQ to SQL Classes. Give proper name "ClubMemberDataClasses.dbml".
Open ClubMemberDataClasses.dbml file and open Server Explorer.
Click on the red push that is "Connect to database". As y'all click on this button, yous volition get the following dialog box.
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.
Now, elevate and drop tblMembers inside ClubMemberDataClasses.dbml.
At present, switch back to HomeController to write INSERT record code into database table using LINQ TO SQL.
Code HomeController.cs
- using ClubMember.Models;
- using Arrangement;
- using Arrangement.Collections.Generic;
- using System.IO;
- using Arrangement.Linq;
- using System.Web;
- using Organization.Web.Mvc;
- using Organization.Configuration;
- namespace ClubMember.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult Near()
- {
- ViewBag.Bulletin ="Your application description page." ;
- return View();
- }
- public ActionResult Contact()
- {
- ViewBag.Bulletin ="Your contact folio." ;
- return View();
- }
- [HttpGet]
- public ActionResult ContactForm()
- {
- return View();
- }
- [HttpPost]
- public ActionResult ContactForm(MemberModel membervalues)
- {
- string FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);
- string FileExtension = Path.GetExtension(membervalues.ImageFile.FileName);
- FileName = DateTime.Now.ToString("yyyyMMdd" )+ "-" +FileName.Trim()+ FileExtension;
- cord UploadPath = ConfigurationManager.AppSettings["UserImagePath" ].ToString();
- membervalues.ImagePath = UploadPath + FileName;
- membervalues.ImageFile.SaveAs(membervalues.ImagePath);
- var db = new ClubMemberDataClassesDataContext();
- tblMember _member =new tblMember();
- _member.ImagePath = membervalues.ImagePath;
- _member.MemberName = membervalues.Name;
- _member.PhoneNumber = membervalues.PhoneNumber;
- db.tblMembers.InsertOnSubmit(_member);
- db.SubmitChanges();
- return View();
- }
- }
- }
Code ContactForm.cshtml
- @model ClubMember.Models.MemberModel
- @{
- ViewBag.Title ="ContactForm" ;
- }
- <h2>ContactForm</h2>
- @using (Html.BeginForm("ContactForm" , "Domicile" ,FormMethod.Post, new { enctype= "multipart/grade-data" }))
- {
- @Html.AntiForgeryToken()
- <divclass = "form-horizontal" >
- <h4>MemberModel</h4>
- <hr />
- @Html.ValidationSummary(truthful , "" , new { @ course = "text-danger" })
- <divform = "class-group" >
- @Html.LabelFor(model => model.Proper name, htmlAttributes:new { @ course = "control-label col-md-2" })
- <divform = "col-doc-10" >
- @Html.EditorFor(model => model.Name,new { htmlAttributes = new { @ class = "course-command" } })
- @Html.ValidationMessageFor(model => model.Name,"" , new { @ grade = "text-danger" })
- </div>
- </div>
- <divclass = "class-group" >
- @Html.LabelFor(model => model.PhoneNumber, htmlAttributes:new { @ class = "control-label col-doctor-2" })
- <divclass = "col-medico-10" >
- @Html.EditorFor(model => model.PhoneNumber,new { htmlAttributes = new { @ class = "form-command" } })
- @Html.ValidationMessageFor(model => model.PhoneNumber,"" , new { @ grade = "text-danger" })
- </div>
- </div>
- <divgrade = "course-group" >
- @Html.LabelFor(model => model.ImagePath, htmlAttributes:new { @ class = "command-label col-medico-2" })
- <divgrade = "col-md-10" >
- <input type="file" name= "ImageFile" required />
- </div>
- </div>
- <divclass = "form-grouping" >
- <divcourse = "col-doctor-offset-2 col-doc-x" >
- <input type="submit" value= "Create" grade = "btn btn-default" />
- </div>
- </div>
- </div>
- }
- <div>
- @Html.ActionLink("Back to Listing" , "Index" )
- </div>
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval" )
- }
Code MemberModel.cs
- using System;
- using Organisation.Collections.Generic;
- using Organisation.ComponentModel;
- using Organisation.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- namespace ClubMember.Models
- {
- public class MemberModel
- {
- [DisplayName("Member Proper name" )]
- public string Proper name { get; set; }
- [DisplayName("Telephone / Mobile Number" )]
- public string PhoneNumber { get; set; }
- [DisplayName("Upload File" )]
- public string ImagePath { go; set; }
- public HttpPostedFileBase ImageFile { get; set; }
- }
- }
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.
Thank yous .
Happy Coding.
Source: https://www.c-sharpcorner.com/article/asp-net-mvc-form-with-file-upload/