Mvc Form With File Upload and Text

Implementation Summary

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

Step past step Implementation

ASP.NET

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

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

Create a "tblMembers" table in the database.

  1. USE [MbkTest]
  2. GO
  3. SET  ANSI_NULLS ON
  4. GO
  5. Set  QUOTED_IDENTIFIER ON
  6. Get
  7. SET  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) Null ,
  13.     [ImagePath] [varchar ](500) NULL ,
  14. PRIMARY Central  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. Become

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

ASP.NET

Click on "Change Hallmark".

ASP.NET

Simply we are looking for the following output.

ASP.NET

Click on "Modify Authentication" button and select No Authentication.

ASP.NET

ASP.NET

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

Right-click on "MODELS" binder or printing CTRL+SHIFT+A to add new Model (CLASS).

ASP.NET

Requite Model Proper noun: "MemberModel".

ASP.NET

Lawmaking of MemberModel.cs

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

Now, build your projection past 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

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

ASP.NET

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

ASP.NET

Equally you click on Add button in VIEWS-->HOME folder CONTACTFORM.CSHTML file will exist created.

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

ASP.NET

At present, permit us change the CSHTML lawmaking.

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  { @ course  = "text-danger"  })

Add the post-obit lines of code.

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

The to a higher place code line is the HTML control for file uploading.

Equally we take changed and usedthe HTML File-Upload control named "ImageFile", so now, permit the states change the model over again to change the titles of fields like this:

  • Proper name = Fellow member Proper noun
  • PhoneNumber = Telephone / Mobile Number
  • ImagePath = Upload File

Code of MemberModel.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using Arrangement.ComponentModel;
  4. using Organization.ComponentModel.DataAnnotations;
  5. using System.Linq;
  6. using System.Spider web;
  7. namespace ClubMember.Models
  8. {
  9. public class  MemberModel
  10.     {
  11.         [DisplayName("Member 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; set; }
  17. public  HttpPostedFileBase ImageFile { get; fix; }
  18.     }
  19. }

Note
DisplayName attribute comes after using the following namespaces.

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

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

ASP.NET

Now, let u.s.a. switch again to ContactForm.cshtml to modify the following.

Line No. 10

@using (Html.BeginForm())

Alter this to:

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

Now, let usa switch back to the controller to work on information technology.

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.At present.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. }

Afterwards 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"  binder is created.

ASP.NET

At present, open web.config file to add APPSETTING.

AppSetting exists nether Configuration Tag.

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

In the to a higher place code, yous can see UserImagePath key created with the value.

Now, fill the form.

ASP.NET

After clicking on CREATE push and submitting the form, you tin can come across your selected file copied in the set folder in web.config.

ASP.NET

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

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

Correct-click on project proper noun "ClubMember".

ASP.NET

Select Information--->LINQ to SQL Classes. Requite proper noun "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 yous click on this push button, you volition get the following dialog box.

ASP.NET

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

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

ASP.NET

Now, drag and drib tblMembers inside ClubMemberDataClasses.dbml.

ASP.NET

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

Lawmaking HomeController.cs

  1. using ClubMember.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using Arrangement.IO;
  5. using System.Linq;
  6. using System.Web;
  7. using Arrangement.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 About()
  18.         {
  19.             ViewBag.Message ="Your application description page." ;
  20. return  View();
  21.         }
  22. public  ActionResult Contact()
  23.         {
  24.             ViewBag.Message ="Your contact folio." ;
  25. render  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.             string 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.Championship ="ContactForm" ;
  4. }
  5. <h2>ContactForm</h2>
  6. @using (Html.BeginForm("ContactForm" , "Abode" ,FormMethod.Mail, new  { enctype= "multipart/form-data"  }))
  7. {
  8.     @Html.AntiForgeryToken()
  9.     <divclass = "form-horizontal" >
  10.         <h4>MemberModel</h4>
  11.         <hour />
  12.         @Html.ValidationSummary(truthful , "" , new  { @ class  = "text-danger"  })
  13.         <divclass = "form-group" >
  14.             @Html.LabelFor(model => model.Name, htmlAttributes:new  { @ class  = "control-characterization col-doc-2"  })
  15.             <divcourse = "col-md-x" >
  16.                 @Html.EditorFor(model => model.Proper name,new  { htmlAttributes = new  { @ form  = "form-control"  } })
  17.                 @Html.ValidationMessageFor(model => model.Name,"" , new  { @ grade  = "text-danger"  })
  18.             </div>
  19.         </div>
  20.         <divclass = "form-group" >
  21.             @Html.LabelFor(model => model.PhoneNumber, htmlAttributes:new  { @ class  = "control-label col-physician-two"  })
  22.             <divclass = "col-dr.-10" >
  23.                 @Html.EditorFor(model => model.PhoneNumber,new  { htmlAttributes = new  { @ course  = "grade-control"  } })
  24.                 @Html.ValidationMessageFor(model => model.PhoneNumber,"" , new  { @ form  = "text-danger"  })
  25.             </div>
  26.         </div>
  27.         <divcourse = "course-group" >
  28.             @Html.LabelFor(model => model.ImagePath, htmlAttributes:new  { @ class  = "control-label col-md-two"  })
  29.             <divform = "col-physician-10" >
  30.                 <input type="file"  name= "ImageFile"  required />
  31.             </div>
  32.         </div>
  33.         <divclass = "grade-group" >
  34.             <divclass = "col-physician-offset-two col-md-ten" >
  35.                 <input type="submit"  value= "Create" class = "btn btn-default"  />
  36.             </div>
  37.         </div>
  38.     </div>
  39. }
  40. <div>
  41.     @Html.ActionLink("Dorsum to Listing" , "Index" )
  42. </div>
  43. @department Scripts {
  44.     @Scripts.Render("~/bundles/jqueryval" )
  45. }

Code MemberModel.cs

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

ASP.NET

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

Await here. The above tape is inserted successfully.

ASP.NET

Thank you .

Happy Coding.

williamsimesers.blogspot.com

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

0 Response to "Mvc Form With File Upload and Text"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel