How to Get Content Type for Upload File in C#
Implementation Summary
- Create a "tblMembers" table in your Database.
- Create a new ASP.Internet 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 tape in tabular array and relieve file in Server.
- Add together Linq To Sql class "ClubMember".
- Insert a record into a database tabular array.
Step by step Implementation
In the to a higher place form, yous tin can see there are iv objects.
- Proper noun Textbox
- Phone Number Textbox
- Image File Upload
- Submit Push
Create a "tblMembers" table in the database.
- USE [MbkTest]
- Go
- SET ANSI_NULLS ON
- Get
- SET QUOTED_IDENTIFIER ON
- Get
- Prepare ANSI_PADDING ON
- Get
- CREATE TABLE [dbo].[tblMembers](
- [MemberID] [int ] IDENTITY(1,1) Not NULL ,
- [MemberName] [varchar ](50) NULL ,
- [PhoneNumber] [varchar ](l) Nil ,
- [ImagePath] [varchar ](500) Cipher ,
- PRIMARY KEY CLUSTERED
- (
- [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.Internet MVC project called "ClubMember".
Click on "Change Authentication".
Merely we are looking for the post-obit output.
Click on "Change Hallmark" button and select No Authentication.
We have created a project called "ClubMember". Now, nosotros are going to add "MemberModel".
Correct-click on "MODELS" binder or press CTRL+SHIFT+A to add together new Model (Grade).
Give Model Name: "MemberModel".
Code of MemberModel.cs
- using Organization;
- using Organization.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace ClubMember.Models
- {
- public class MemberModel
- {
- public string Name { get; set; }
- public string PhoneNumber { get; set; }
- public string ImagePath { get; gear up; }
- public HttpPostedFile ImageFile { go; set; }
- }
- }
At present, build your project by right-clicking on the project and selecting BUILD.
Now, switch to HOME Controller. Click on Controllers binder and double click on HOMECONTROLLER.CS file.
Create an activeness-method chosen CONTACTFORM.
By default, the Add together View dialog box will display as below.
Fill up the "Add VIEW" dialog box with the post-obit values.
Every bit you click on Add together button in VIEWS-->Abode folder CONTACTFORM.CSHTML file will be created.
Switch to CONTACTFORM.CSHTML file and press F5. The output screen is given beneath.
Now, let us modify the CSHTML code.
Switch to CONTACTFORM.CSHTML file, practice the following changes and press F5.
Remove following code of ImagePath
- @Html.EditorFor(model => model.ImagePath, new { htmlAttributes = new { @ grade = "form-command" } })
- @Html.ValidationMessageFor(model => model.ImagePath,"" , new { @ class = "text-danger" })
Add together the post-obit lines of code.
- <input type= "file" name= "ImageFile" required />
The above code line is the HTML control for file uploading.
Equally we take changed and usedthe HTML File-Upload control named "ImageFile", so now, permit us change the model again to change the titles of fields similar this:
- Name = Member Proper name
- PhoneNumber = Phone / Mobile Number
- ImagePath = Upload File
Code of MemberModel.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using Arrangement.ComponentModel.DataAnnotations;
- using Arrangement.Linq;
- using System.Web;
- namespace ClubMember.Models
- {
- public course MemberModel
- {
- [DisplayName("Member Proper name" )]
- public string Name { get; set; }
- [DisplayName("Telephone / Mobile Number" )]
- public string PhoneNumber { get; set; }
- [DisplayName("Upload File" )]
- public string ImagePath { get; prepare; }
- public HttpPostedFileBase ImageFile { get; set; }
- }
- }
Note
DisplayName attribute comes afterwards using the following namespaces.
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
At present, again, switch to CONTACTFORM.CSHTML file, exercise the following changes and press F5.
Now, allow us switch once again to ContactForm.cshtml to change the following.
Line No. 10
@using (Html.BeginForm())
Change this to:
- @using(Html.BeginForm( "ContactForm" , "Habitation" , FormMethod.Mail, new
- {
- enctype ="multipart/form-data"
- }))
Now, let us switch back to the controller to work on it.
- [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;
- string UploadPath = ConfigurationManager.AppSettings["UserImagePath" ].ToString();
- membervalues.ImagePath = UploadPath + FileName;
- membervalues.ImageFile.SaveAs(membervalues.ImagePath);
- return View();
- }
After updating the HTTPPOST code, now, it is time to create a new folder called "UserImages".
You tin see in the Solution Explorer folder that the "UserImages" folder is created.
Now, open web.config file to add APPSETTING.
AppSetting exists under Configuration Tag.
- <configuration>
- <appSettings>
- <add key="webpages:Version" value= "3.0.0.0" />
- <add key="webpages:Enabled" value= "false" />
- <add key="ClientValidationEnabled" value= "true" />
- <add key="UnobtrusiveJavaScriptEnabled" value= "true" />
- <add key="UserImagePath" value= "D:\MBK\ClubMember\ClubMember\UserImages\" />
- </appSettings>
In the higher up code, you can meet UserImagePath cardinal created with the value.
At present, fill the form.
Later on clicking on CREATE push and submitting the form, y'all can run across your selected file copied in the set binder in spider web.config.
Now, we are going to write the code to store other information of CONTACT Form details.
- Member Name
- Telephone/Mobile Number
- Epitome File Path
Correct-click on project proper name "ClubMember".
Select Data--->LINQ to SQL Classes. Give name "ClubMemberDataClasses.dbml".
Open ClubMemberDataClasses.dbml file and open Server Explorer.
Click on the red button that is "Connect to database". Every bit you click on this push button, you will get the following dialog box.
In the above dialog box, you take to provide a Database server proper name and Authentication level and afterward, select your database.
Now, you tin see database is opened in Server Explorer.
Now, drag and drop tblMembers inside ClubMemberDataClasses.dbml.
Now, switch back to HomeController to write INSERT record lawmaking into database table using LINQ TO SQL.
Code HomeController.cs
- using ClubMember.Models;
- using Organisation;
- using System.Collections.Generic;
- using System.IO;
- using Organisation.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Configuration;
- namespace ClubMember.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult Most()
- {
- ViewBag.Message ="Your application description folio." ;
- return View();
- }
- public ActionResult Contact()
- {
- ViewBag.Bulletin ="Your contact folio." ;
- return View();
- }
- [HttpGet]
- public ActionResult ContactForm()
- {
- return View();
- }
- [HttpPost]
- public ActionResult ContactForm(MemberModel membervalues)
- {
- cord FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);
- cord 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.Proper noun;
- _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/course-data" }))
- {
- @Html.AntiForgeryToken()
- <divclass = "class-horizontal" >
- <h4>MemberModel</h4>
- <hr />
- @Html.ValidationSummary(true , "" , new { @ course = "text-danger" })
- <divclass = "form-group" >
- @Html.LabelFor(model => model.Name, htmlAttributes:new { @ grade = "control-characterization col-md-two" })
- <divclass = "col-md-ten" >
- @Html.EditorFor(model => model.Name,new { htmlAttributes = new { @ form = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name,"" , new { @ form = "text-danger" })
- </div>
- </div>
- <divgrade = "class-grouping" >
- @Html.LabelFor(model => model.PhoneNumber, htmlAttributes:new { @ grade = "control-label col-md-two" })
- <divform = "col-physician-10" >
- @Html.EditorFor(model => model.PhoneNumber,new { htmlAttributes = new { @ class = "course-control" } })
- @Html.ValidationMessageFor(model => model.PhoneNumber,"" , new { @ grade = "text-danger" })
- </div>
- </div>
- <divclass = "form-group" >
- @Html.LabelFor(model => model.ImagePath, htmlAttributes:new { @ form = "control-label col-md-2" })
- <divform = "col-md-10" >
- <input type="file" proper noun= "ImageFile" required />
- </div>
- </div>
- <divclass = "course-group" >
- <divclass = "col-md-get-go-ii col-md-10" >
- <input type="submit" value= "Create" grade = "btn btn-default" />
- </div>
- </div>
- </div>
- }
- <div>
- @Html.ActionLink("Back to Listing" , "Index" )
- </div>
- @department Scripts {
- @Scripts.Render("~/bundles/jqueryval" )
- }
Code MemberModel.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using Organisation.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- namespace ClubMember.Models
- {
- public class MemberModel
- {
- [DisplayName("Member Name" )]
- public string Name { get; prepare; }
- [DisplayName("Telephone / Mobile Number" )]
- public string PhoneNumber { go; set up; }
- [DisplayName("Upload File" )]
- public string ImagePath { get; set; }
- public HttpPostedFileBase ImageFile { get; gear up; }
- }
- }
Now, you can check in your SQL Server database tabular array if the tape is inserted or not.
Wait here. The above record is inserted successfully.
Thank you .
Happy Coding.
Source: https://www.c-sharpcorner.com/article/asp-net-mvc-form-with-file-upload/
0 Response to "How to Get Content Type for Upload File in C#"
Post a Comment