How to Get Content Type for Upload File in C#

Implementation Summary

  1. Create a "tblMembers" table in your Database.
  2. Create a new ASP.Internet 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 tape in tabular array and relieve file in Server.
  8. Add together Linq To Sql class "ClubMember".
  9. Insert a record into a database tabular array.

Step by step Implementation

ASP.NET

In the to a higher place form, yous tin can see there are iv 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. SET  ANSI_NULLS ON
  4. Get
  5. SET  QUOTED_IDENTIFIER ON
  6. Get
  7. Prepare  ANSI_PADDING ON
  8. Get
  9. CREATE TABLE  [dbo].[tblMembers](
  10.     [MemberID] [int ] IDENTITY(1,1) Not NULL ,
  11.     [MemberName] [varchar ](50) NULL ,
  12.     [PhoneNumber] [varchar ](l) Nil ,
  13.     [ImagePath] [varchar ](500) Cipher ,
  14. PRIMARY KEY  CLUSTERED
  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.Internet MVC project called "ClubMember".

ASP.NET

Click on "Change Authentication".

ASP.NET

Merely we are looking for the post-obit output.

ASP.NET

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

ASP.NET

ASP.NET

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).

ASP.NET

Give Model Name: "MemberModel".

ASP.NET

Code of MemberModel.cs

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

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

ASP.NET

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

Create an activeness-method chosen CONTACTFORM.

ASP.NET

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

ASP.NET

Fill up the "Add VIEW" dialog box with the post-obit values.

ASP.NET

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.

ASP.NET

Now, let us modify the CSHTML code.

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

ASP.NET

Remove following code of ImagePath

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

Add together the post-obit lines of code.

  1. <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

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

Note
DisplayName attribute comes afterwards using the following namespaces.

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

At present, again, switch to CONTACTFORM.CSHTML file, exercise the following changes and press F5.

ASP.NET

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

Line No. 10

@using (Html.BeginForm())

Change this to:

  1. @using(Html.BeginForm( "ContactForm" , "Habitation" , FormMethod.Mail, 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.     string FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);
  5.     string FileExtension = Path.GetExtension(membervalues.ImageFile.FileName);
  6.     FileName = DateTime.Now.ToString("yyyyMMdd" )+ "-" +FileName.Trim()+ FileExtension;
  7.     string UploadPath = ConfigurationManager.AppSettings["UserImagePath" ].ToString();
  8.     membervalues.ImagePath = UploadPath + FileName;
  9.     membervalues.ImageFile.SaveAs(membervalues.ImagePath);
  10. return  View();
  11. }

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

ASP.NET

You tin 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 higher up code, you can meet UserImagePath cardinal created with the value.

At present, fill the form.

ASP.NET

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.

ASP.NET

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".

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". Every bit you click on this push button, you will get the following dialog box.

ASP.NET

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.

ASP.NET

Now, drag and drop tblMembers inside ClubMemberDataClasses.dbml.

ASP.NET

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

Code HomeController.cs

  1. using ClubMember.Models;
  2. using Organisation;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using Organisation.Linq;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. using System.Configuration;
  9. namespace ClubMember.Controllers
  10. {
  11. public class  HomeController : Controller
  12.     {
  13. public  ActionResult Index()
  14.         {
  15. return  View();
  16.         }
  17. public  ActionResult Most()
  18.         {
  19.             ViewBag.Message ="Your application description folio." ;
  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.             cord FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);
  36.             cord 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.Proper noun;
  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/course-data"  }))
  7. {
  8.     @Html.AntiForgeryToken()
  9.     <divclass = "class-horizontal" >
  10.         <h4>MemberModel</h4>
  11.         <hr />
  12.         @Html.ValidationSummary(true , "" , new  { @ course  = "text-danger"  })
  13.         <divclass = "form-group" >
  14.             @Html.LabelFor(model => model.Name, htmlAttributes:new  { @ grade  = "control-characterization col-md-two"  })
  15.             <divclass = "col-md-ten" >
  16.                 @Html.EditorFor(model => model.Name,new  { htmlAttributes = new  { @ form  = "form-control"  } })
  17.                 @Html.ValidationMessageFor(model => model.Name,"" , new  { @ form  = "text-danger"  })
  18.             </div>
  19.         </div>
  20.         <divgrade = "class-grouping" >
  21.             @Html.LabelFor(model => model.PhoneNumber, htmlAttributes:new  { @ grade  = "control-label col-md-two"  })
  22.             <divform = "col-physician-10" >
  23.                 @Html.EditorFor(model => model.PhoneNumber,new  { htmlAttributes = new  { @ class  = "course-control"  } })
  24.                 @Html.ValidationMessageFor(model => model.PhoneNumber,"" , new  { @ grade  = "text-danger"  })
  25.             </div>
  26.         </div>
  27.         <divclass = "form-group" >
  28.             @Html.LabelFor(model => model.ImagePath, htmlAttributes:new  { @ form  = "control-label col-md-2"  })
  29.             <divform = "col-md-10" >
  30.                 <input type="file"  proper noun= "ImageFile"  required />
  31.             </div>
  32.         </div>
  33.         <divclass = "course-group" >
  34.             <divclass = "col-md-get-go-ii col-md-10" >
  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. @department Scripts {
  44.     @Scripts.Render("~/bundles/jqueryval" )
  45. }

Code MemberModel.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.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 Name" )]
  12. public  string Name { get; prepare; }
  13.         [DisplayName("Telephone / Mobile Number" )]
  14. public  string PhoneNumber { go; set up; }
  15.         [DisplayName("Upload File" )]
  16. public  string ImagePath { get; set; }
  17. public  HttpPostedFileBase ImageFile { get; gear up; }
  18.     }
  19. }

ASP.NET

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.

ASP.NET

Thank you .

Happy Coding.

woodsandsorses.blogspot.com

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel