Mvc Form With File Upload and Text
Implementation Summary
- Create a "tblMembers" table in your Database.
- Create a new ASP.NET MVC spider web awarding project called "ClubMember".
- Create a Model called "MemberModel".
- Create HTTPGET ActionMethod chosen "ContactForm".
- Create a view of "ContactForm".
- Use HTML File Upload command.
- Create HTTPPOST ActionMethod chosen "ContactForm" to insert record in table and salve file in Server.
- Add Linq To Sql class "ClubMember".
- Insert a tape into a database table.
Step past step Implementation
In the above form, you can meet there are four objects.
- Name Textbox
- Phone Number Textbox
- Prototype File Upload
- Submit Button
Create a "tblMembers" table in the database.
- USE [MbkTest]
- GO
- SET ANSI_NULLS ON
- GO
- Set QUOTED_IDENTIFIER ON
- Get
- SET ANSI_PADDING ON
- Get
- CREATE TABLE [dbo].[tblMembers](
- [MemberID] [int ] IDENTITY(1,1) NOT NULL ,
- [MemberName] [varchar ](50) Null ,
- [PhoneNumber] [varchar ](l) Null ,
- [ImagePath] [varchar ](500) NULL ,
- PRIMARY Central 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
- Become
Create a new ASP.NET MVC project chosen "ClubMember".
Click on "Change Hallmark".
Simply we are looking for the following output.
Click on "Modify Authentication" button and select No Authentication.
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).
Requite Model Proper noun: "MemberModel".
Lawmaking of MemberModel.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Spider web;
- namespace ClubMember.Models
- {
- public class MemberModel
- {
- public string Name { become; set up; }
- public cord PhoneNumber { get; set; }
- public cord ImagePath { get; fix; }
- public HttpPostedFile ImageFile { get; set; }
- }
- }
Now, build your projection past right-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 action-method called CONTACTFORM.
Past default, the Add View dialog box will display as below.
Fill the "ADD VIEW" dialog box with the following values.
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.
At present, permit us change the CSHTML lawmaking.
Switch to CONTACTFORM.CSHTML file, do the following changes and press F5.
Remove following code of ImagePath
- @Html.EditorFor(model => model.ImagePath, new { htmlAttributes = new { @ class = "form-control" } })
- @Html.ValidationMessageFor(model => model.ImagePath,"" , new { @ course = "text-danger" })
Add the post-obit lines of code.
- <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
- using System;
- using System.Collections.Generic;
- using Arrangement.ComponentModel;
- using Organization.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Spider web;
- namespace ClubMember.Models
- {
- public class MemberModel
- {
- [DisplayName("Member Name" )]
- public string Name { get; set; }
- [DisplayName("Telephone / Mobile Number" )]
- public string PhoneNumber { get; set; }
- [DisplayName("Upload File" )]
- public string ImagePath { get; set; }
- public HttpPostedFileBase ImageFile { get; fix; }
- }
- }
Note
DisplayName attribute comes after using the following namespaces.
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
At present, again, switch to CONTACTFORM.CSHTML file, do the following changes and press F5.
Now, let u.s.a. switch again to ContactForm.cshtml to modify the following.
Line No. 10
@using (Html.BeginForm())
Alter this to:
- @using(Html.BeginForm( "ContactForm" , "Home" , FormMethod.Post, new
- {
- enctype ="multipart/class-data"
- }))
Now, let usa switch back to the controller to work on information technology.
- [HttpPost]
- public ActionResult ContactForm(MemberModel membervalues)
- {
- string FileName = Path.GetFileNameWithoutExtension(membervalues.ImageFile.FileName);
- string FileExtension = Path.GetExtension(membervalues.ImageFile.FileName);
- FileName = DateTime.At present.ToString("yyyyMMdd" )+ "-" +FileName.Trim()+ FileExtension;
- string UploadPath = ConfigurationManager.AppSettings["UserImagePath" ].ToString();
- membervalues.ImagePath = UploadPath + FileName;
- membervalues.ImageFile.SaveAs(membervalues.ImagePath);
- return View();
- }
Afterwards updating the HTTPPOST code, now, it is time to create a new folder called "UserImages".
You can see in the Solution Explorer folder that the "UserImages" binder is created.
At present, open web.config file to add APPSETTING.
AppSetting exists nether Configuration Tag.
- <configuration>
- <appSettings>
- <add together cardinal="webpages:Version" value= "iii.0.0.0" />
- <add key="webpages:Enabled" value= "false" />
- <add key="ClientValidationEnabled" value= "truthful" />
- <add cardinal="UnobtrusiveJavaScriptEnabled" value= "true" />
- <add together key="UserImagePath" value= "D:\MBK\ClubMember\ClubMember\UserImages\" />
- </appSettings>
In the to a higher place code, yous can see UserImagePath key created with the value.
Now, fill the form.
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.
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".
Select Information--->LINQ to SQL Classes. Requite proper noun "ClubMemberDataClasses.dbml".
Open ClubMemberDataClasses.dbml file and open Server Explorer.
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.
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.
Now, drag and drib tblMembers inside ClubMemberDataClasses.dbml.
At present, switch back to HomeController to write INSERT record code into database table using LINQ TO SQL.
Lawmaking HomeController.cs
- using ClubMember.Models;
- using System;
- using System.Collections.Generic;
- using Arrangement.IO;
- using System.Linq;
- using System.Web;
- using Arrangement.Web.Mvc;
- using System.Configuration;
- namespace ClubMember.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult About()
- {
- ViewBag.Message ="Your application description page." ;
- return View();
- }
- public ActionResult Contact()
- {
- ViewBag.Message ="Your contact folio." ;
- render 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;
- string 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.Championship ="ContactForm" ;
- }
- <h2>ContactForm</h2>
- @using (Html.BeginForm("ContactForm" , "Abode" ,FormMethod.Mail, new { enctype= "multipart/form-data" }))
- {
- @Html.AntiForgeryToken()
- <divclass = "form-horizontal" >
- <h4>MemberModel</h4>
- <hour />
- @Html.ValidationSummary(truthful , "" , new { @ class = "text-danger" })
- <divclass = "form-group" >
- @Html.LabelFor(model => model.Name, htmlAttributes:new { @ class = "control-characterization col-doc-2" })
- <divcourse = "col-md-x" >
- @Html.EditorFor(model => model.Proper name,new { htmlAttributes = new { @ form = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name,"" , new { @ grade = "text-danger" })
- </div>
- </div>
- <divclass = "form-group" >
- @Html.LabelFor(model => model.PhoneNumber, htmlAttributes:new { @ class = "control-label col-physician-two" })
- <divclass = "col-dr.-10" >
- @Html.EditorFor(model => model.PhoneNumber,new { htmlAttributes = new { @ course = "grade-control" } })
- @Html.ValidationMessageFor(model => model.PhoneNumber,"" , new { @ form = "text-danger" })
- </div>
- </div>
- <divcourse = "course-group" >
- @Html.LabelFor(model => model.ImagePath, htmlAttributes:new { @ class = "control-label col-md-two" })
- <divform = "col-physician-10" >
- <input type="file" name= "ImageFile" required />
- </div>
- </div>
- <divclass = "grade-group" >
- <divclass = "col-physician-offset-two col-md-ten" >
- <input type="submit" value= "Create" class = "btn btn-default" />
- </div>
- </div>
- </div>
- }
- <div>
- @Html.ActionLink("Dorsum to Listing" , "Index" )
- </div>
- @department Scripts {
- @Scripts.Render("~/bundles/jqueryval" )
- }
Code MemberModel.cs
- using Arrangement;
- using System.Collections.Generic;
- using Arrangement.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using Arrangement.Linq;
- using System.Web;
- namespace ClubMember.Models
- {
- public class MemberModel
- {
- [DisplayName("Fellow member Name" )]
- public string Name { get; set; }
- [DisplayName("Telephone / Mobile Number" )]
- public string PhoneNumber { get; fix; }
- [DisplayName("Upload File" )]
- public cord ImagePath { get; set; }
- public HttpPostedFileBase ImageFile { go; set; }
- }
- }
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.
Thank you .
Happy Coding.
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