How to save data using jquery in asp.net

In this article I provide a quick overview of how to insert a record into SQL Server using jQuery. 

First we create a database table named "TblUser".


Creating SQL Database Table

CREATE TABLE [dbo].[TblUser](
      [Name] [varchar](50) NULL,
      [Email] [varchar](100) NULL
)
Now execute the above code in your  SQL query windows.

Now Open your Visual Studio sample Project.
Create a New webPage name it as SampleJson

In SampleJson.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SampleJson.aspx.cs" Inherits="SrikrishnaEnterprise.SampleJson" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>AutoComplete Box with jQuery</title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
        rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
       <script type="text/javascript">
           $(document).ready(function () {
               $('#Button1').click(function () {
                   $.ajax({
                       type: 'POST',
                       contentType: "application/json; charset=utf-8",
                       url: 'SampleJson.aspx/InsertMethod',
                       data: "{'Name':'" + document.getElementById('txtUserName').value + "', 'Email':'" + document.getElementById('txtEmail').value + "'}",
                       async: false,
                       success: function (response) {
                           $('#txtUserName').val('');
                           $('#txtEmail').val('');
                           alert("Record Has been Saved in Database");
                       },
                       error: function ()
                       { console.log('there is some error'); }
                   });
               });
           });      
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="demo">
        <div class="ui-widget">
            <label for="tbAuto">
                Enter UserName:
            </label>
&nbsp;<asp:TextBox ID="txtUserName" runat="server" ClientIDMode="Static" Width="202px"></asp:TextBox>
            <br />
            <br />
            Email: <asp:TextBox ID="txtEmail" runat="server" ClientIDMode="Static" Width="210px"></asp:TextBox>
            <br />
            <br />           
            <asp:Button ID="Button1" runat="server" Text="Button" ClientIDMode="Static" />
        </div>
    </div>
    </form>
</body>
</html>


In SampleJson.aspx.cs
using System;
using System.Collections.Generic;
sing System.Data.SqlClient;
using System.Web.Services;
using System.Web;
using System.Data;
namespace YourNameSpace
{
    public partial class SampleJson : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string InsertMethod(string Name, string Email)
        {
             //Change your datasource name
            SqlConnection con = new SqlConnection("Data Source="./SQlExpress";Initial Catalog=Sample;Integrated Security=true;");
            {
                SqlCommand cmd = new SqlCommand("Insert into TestTable values('" + Name + "', '" + Email + "')", con);
                {
                    con.Open();
                    cmd.ExecuteNonQuery();
                    return "True";
                }
            }

        }
    }
}


Set Start page as SampleJson.aspx and Run this Project.



Enter UserName and Email Address then Click Button.




Now going to your SQL New Query window

Just run this Query
Select * from TblUser



Now you can successfully save data using Jquery in asp.net Enviroinment.


How to validate textbox with default value

            <asp:TextBox ID="txtEmail" Height="43px" runat="server" Text="Email" OnFocus="ClearText(this)" onfocusout="ResetText(this)" ForeColor="#333333" ></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" Display="Dynamic" ControlToValidate="txtEmail" InitialValue="Email" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>

In your RequiredFieldValidator have a InitialValue Property, You have enter the default value of your textbox value. Thats it.

How to set default value in password textbox

<script type="text/javascript">

    function ClearText(txt) {
        if (txt.defaultValue == txt.value) txt.value = "";
if (txt.defaultValue == "Password") {
            txt.type = 'password';
        }
    }
    function ResetText(txt) {
        if (txt.value == "") {
            txt.value = txt.defaultValue;
            txt.type = 'text';
        }
    }

</script>

<asp:TextBox ID="txtPassword" Height="43px" runat="server" onclick="this.value=''; this.type='password';" Text="Password" OnFocus="ClearText(this)" onfocusout="ResetText(this)" ForeColor="#333333" ></asp:TextBox>