Introduction
In this blog, we will discuss how to show an image preview before uploading to a database in ASP.NET. We will save the image path in the database and the image in the images folder of our project. This form has all textbox, dropdown list, and file upload controller validation.
Step 1
Create a database in the MS SQL Server of your choice.
- CREATE TABLE [dbo].[Employee](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [First_Name] [nvarchar](50) NULL,
- [Last_name] [nvarchar](50) NULL,
- [Gender] [char](10) NULL,
- [DateofBirth] [nvarchar](50) NULL,
- [Phone_Number] [nvarchar](50) NULL,
- [Email] [nvarchar](50) NULL,
- [Image] [nvarchar](50) NULL,
- [Created] [datetime] NULL,
- CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
-
- Create procedure [dbo].[spAddNewlEmplyee]
- (
- @First_Name nvarchar(50),
- @Last_Name nvarchar(50),
- @Gender char(10),
- @DateofBirth nvarchar(50),
- @Phone_Number nvarchar(50),
- @Email nvarchar(50),
- @Image nvarchar(50),
- @Created nvarchar(50)
- )
- as
- begin
- insert into Employee(First_Name,Last_Name,Gender,DateofBirth,Phone_Number,Email,Image,Created)
- values(@First_Name,@Last_Name,@Gender,@DateofBirth,@Phone_Number,@Email,@Image,GETDATE())
- end
-
- Create procedure [dbo].[spGetAllEmplyee]
- as
- begin
- select* from Employee
- end
Step 2
Create a web project with an empty template, give it a meaningful name. Right-click and add a new item, choose a web form and give it a name. Open web.config file to add a connection to your project.
- <connectionStrings>
- <add name="DBCS" connectionString="data source=FARHAN\SQLEXPRESS; database=EmployeeDB; Integrated Security=true;" providerName="System.Data.SqlClient"/>
- </connectionStrings>
Step 3
Add a validation setting for validation control in the webconfig file of your project.
- <appSettings>
- <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
- </appSettings>
Step 4
Add the script and style CDN links in the head section.
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
- <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
- <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Step 5
Write a function for image preview in jQuery.
- <script type="text/javascript">
-
- function ShowImagePreview(input) {
- if (input.files && input.files[0]) {
- var reader = new FileReader();
- reader.onload = function (e) {
- $('#imagePreview').prop('src', e.target.result);
- };
- reader.readAsDataURL(input.files[0]);
- }
- }
-
- $(document).ready(function () {
- $('#txtDateofBirth').datepicker({
- changeMonth: true,
- changeYear: true,
- dateFormat: "dd-mm-yy",
- yearRange: "-100:+10"
- });
- });
- </script>
Step 6
Design the HTML as given below.
Step-7
Write C# back-end code for Submit button, Reset button, and binding the Grid View.
- using System;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.IO;
-
- namespace ShowImagePreviewBeforUpload
- {
- public partial class ShowImgePreview : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindEmployeeGrid();
- }
- }
-
- private void BindEmployeeGrid()
- {
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con=new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetAllEmplyee",con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- EmployeeGridView.DataSource=cmd.ExecuteReader();
- EmployeeGridView.DataBind();
- }
- }
-
- protected void btnSubmit_Click(object sender, EventArgs e)
- {
- try
- {
- if (ProfileFileUpload.PostedFile != null)
- {
- string FileName = Path.GetFileName(ProfileFileUpload.PostedFile.FileName);
- ProfileFileUpload.SaveAs(Server.MapPath("/images" + FileName));
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spAddNewlEmplyee", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@First_Name",txtFisrtName.Text.Trim());
- cmd.Parameters.AddWithValue("@Last_Name",txtLastName.Text.Trim());
- cmd.Parameters.AddWithValue("@Gender",ddlGender.SelectedItem.Value);
- cmd.Parameters.AddWithValue("@DateofBirth",txtDateofBirth.Text.Trim());
- cmd.Parameters.AddWithValue("@Phone_Number",txtPhoneNumber.Text.Trim());
- cmd.Parameters.AddWithValue("@Email",txtEmail.Text.Trim());
- cmd.Parameters.AddWithValue("@Image","images"+ FileName);
- cmd.Parameters.AddWithValue("@Created", DateTime.Now);
- cmd.ExecuteNonQuery();
- BindEmployeeGrid();
- lblMessage.Text = "Your record submitted successfully";
- lblMessage.ForeColor = System.Drawing.Color.Green;
-
- }
- }
- }
- catch (Exception)
- {
- lblMessage.Text = "Your record not submitted";
- lblMessage.ForeColor = System.Drawing.Color.Red;
- }
- }
-
- protected void btnReset_Click(object sender, EventArgs e)
- {
- txtFisrtName.Text= string.Empty;
- txtLastName.Text = string.Empty;
- txtDateofBirth.Text = string.Empty;
- txtPhoneNumber.Text = string.Empty;
- txtEmail.Text = string.Empty;
- }
- }
- }
Step 8
Run the project by pressing ctr+F5.