Implementation Summary
- Create a “tblMembers” table 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 record into a database table.
Step by step Implementation
In the above form, you can see there are four objects.
- Name Textbox
- Phone Number Textbox
- Image File Upload
- Submit Button
Create a “tblMembers” table in the database.
- USE [MbkTest]
- GO
-
- SET ANSI_NULLS ON
- GO
-
- SET QUOTED_IDENTIFIER ON
- GO
-
- SET ANSI_PADDING ON
- GO
-
- CREATE TABLE [dbo].[tblMembers](
- [MemberID] [int] IDENTITY(1,1) NOT NULL,
- [MemberName] [varchar](50) NULL,
- [PhoneNumber] [varchar](50) NULL,
- [ImagePath] [varchar](500) NULL,
- 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.NET MVC project called “ClubMember”.
Click on “Change Authentication”.
But we are looking for the following output.
Click on “Change Authentication” button and select No Authentication.
We have created a project called “ClubMember“. Now, we are going to add “MemberModel”.
Right-click on “MODELS” folder or press CTRL+SHIFT+A to add new Model (CLASS).
Give Model Name: “MemberModel”.
Code of MemberModel.cs
- using System;
- using System.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; set; }
- public HttpPostedFile ImageFile { get; set; }
- }
- }
Now, build your project by 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.
By default, the Add View dialog box will display as below.
Fill the "ADD VIEW" dialog box with the following values.
As you click on ADD button in VIEWS-->HOME folder CONTACTFORM.CSHTML file will be created.
Switch to CONTACTFORM.CSHTML file and press F5. The output screen is given below.
Now, let us modify the CSHTML code.
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 { @class = "text-danger" })
Add the following lines of code.
- <input type="file" name="ImageFile" required />
The above code line is the HTML control for file uploading.
As we have changed and usedthe HTML File-Upload control named ”ImageFile”, so now, let us change the model again to change the titles of fields like this:
- Name = Member Name
- PhoneNumber = Telephone / Mobile Number
- ImagePath = Upload File
Code of MemberModel.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.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; set; }
- }
- }
Note
DisplayName attribute comes after using the following namespaces.
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
Now, again, switch to CONTACTFORM.CSHTML file, do the following changes and press F5.
Now, let us switch again to ContactForm.cshtml to change the following.
Line No. 10
@using (Html.BeginForm())
Change this to:
- @using(Html.BeginForm("ContactForm", "Home", FormMethod.Post, 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 can 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 above code, you can see UserImagePath key created with the value.
Now, fill the form.
After clicking on CREATE button and submitting the form, you can see your selected file copied in the set folder in web.config.
Now, we 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 project 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”. As you click on this button, you will get the following dialog box.
In the above dialog box, you have to provide a Database server name and Authentication level and afterward, select your database.
Now, you can see database is opened in Server Explorer.
Now, drag and drop tblMembers inside ClubMemberDataClasses.dbml.
Now, switch back to HomeController to write INSERT record code into database table using LINQ TO SQL.
Code HomeController.cs
- using ClubMember.Models;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.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 About()
- {
- ViewBag.Message = "Your application description page.";
-
- return View();
- }
-
- public ActionResult Contact()
- {
- ViewBag.Message = "Your contact page.";
-
- 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;
-
-
- 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.Title = "ContactForm";
- }
-
- <h2>ContactForm</h2>
-
-
- @using (Html.BeginForm("ContactForm","Home",FormMethod.Post,new { enctype="multipart/form-data" }))
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- <h4>MemberModel</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.ImagePath, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- <input type="file" name="ImageFile" required />
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
-
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
-
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
Code MemberModel.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.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; set; }
- }
- }
Now, you can check in your SQL Server database table if the record is inserted or not.
Look here. The above record is inserted successfully.
Thank you .
Happy Coding.