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>


How to use alert message from base class

In your base class for example,
Utils.cs write the following method

public static void ShowAlert(Page currentPage, string message)
      {
          StringBuilder sb = new StringBuilder();
          sb.Append("alert('");
          sb.Append(message);
          sb.Append("');");
          currentPage.ClientScript.RegisterStartupScript(typeof(Utils), "showalert", sb.ToString(), true);
      }

Now where ever you want to show your alert message just call it.

for example

In Hello.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
       Utils.ShowAlert(this, "Hello");
}

How to div hide and show using c# in codebehind

In .aspx

<div id="divhide" runat="server">

<p>Test</p>

</div>

use anchor tag runat="server"

In .aspx.cs

In any event

divhide.Visible = true or false; // based on your needs.

How to change Data format in Jquery DataPicker

<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=txtDate.ClientID %>").datepicker({
        dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true
        });
    });
</script>


In this dateFormat field you have to specify your custom format.

Simple way to make current menu as different color using jquery

In your Master page you can add this code.

  <script type="text/javascript">

        $(document).ready(function () {

            var activeMenu = $('#activeSubMenu').val();

            $('#subMenu li').each(function () {
                var currentVal = $(this).attr('id');
                if (currentVal == activeMenu) {
                    $(this).addClass('ActiveMenu');
                } else {
                    $(this).removeClass('ActiveMenu');
                }
            });

        });

</script>

<ul id="subMenu">
            <li id="module">
                <a id="A7" runat="server" href="~/Settings/Modules.aspx">
                Modules</a></li>
            <li id="operation">
                <a id="A8" runat="server" href="~/Settings/Operation.aspx">Operations</a></li>
            <li id="role">
                <a id="A9" runat="server" href="~/Settings/Role.aspx">Roles</a></li>
</ul>

In this <li> id's i have given the name as module, operation, role.

In this each page Modules.aspx, Operation.aspx, Role.aspx you can add hidden field like wise

    <input type="hidden" id="activeSubMenu" value="module" />. Here you can gave the value is SubMenu <li> id values.

for ex.
 In Modules.aspx,
    <input type="hidden" id="activeSubMenu" value="module" />
 Operation.aspx, 
    <input type="hidden" id="activeSubMenu" value="operation" />
Role.aspx
    <input type="hidden" id="activeSubMenu" value="role" />

In CSS

.ActiveMenu
{
background-color: #AAD4FF !important;
font-weight: 600;
}



How to avoid page jump to top position after failed validation?

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" MaintainScrollPositionOnPostback="true" %>

You have just add MaintainScrollPositionOnPostback="true" in page directive.

It will maintain your page position.

How to lock Screen While Saving in asp.net

<style type="text/css">
      .LockOff {
         display: none;
         visibility: hidden;
      }

      .LockOn {
         display: block;
         visibility: visible;
         position: absolute;
         z-index: 999;
         top: 0px;
         left: 0px;
         width: 100%;
          min-height:1000px;
         color:Green;
         background-color: #ccc;
         text-align: center;
         padding-top: 30%;
         font-size:large;
         filter: alpha(opacity=75);
         opacity: 0.75;
      }
   </style>

   <script type="text/javascript">
       function skm_LockScreen(str) {
           var lock = document.getElementById('skm_LockPane');
           if (lock)
               lock.className = 'LockOn';

           lock.innerHTML = str;
       }
   </script>

<div id="skm_LockPane" class="LockOff"></div>

                                            <asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="skm_LockScreen('We are processing your request...');" OnClick="btnSave_Click" CausesValidation="false" />

How to save Image into database

protected void btnSave_Click(object sender, EventArgs e)
        {

            //Get Image into byte
            Stream fs = FileUpload1.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);
         }

In .aspx

<script type="text/javascript">
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#blah').attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }
   </script>


<table>
                                    <tr>
                                        <td colspan="2" style="border:1px #ccc solid; padding:10px;" >
                                            EmpId
                                        
                                            <asp:TextBox ID="txtEmpId" runat="server"></asp:TextBox>
                                        </td>
                                        <td  align="right" style="border:1px #ccc solid; padding:20px;">
                                            Upload Photo
                                            <asp:FileUpload ID="FileUpload1" runat="server" onchange="readURL(this)" Width="250px" style="border:1px #ccc solid;" />
                                        </td>
                                        <td width="150px" style="border:1px #ccc solid; padding:10px;">
                                            <img id="blah" src="../../Images/View/ad1.jpg" alt="" style="height:150px; width:150px;" />
                                        </td>
                                    </tr>
                                </table>

DatePicker in Asp.net using jquery

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
            <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/base/jquery-ui.css" type="text/css" media="all" />
   <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
   <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js" type="text/javascript"></script>


    <script type="text/javascript">
        $(function () {
            $("#<%= txtFoo.ClientID  %>").datepicker();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input runat="server" type="text" id="txtFoo"  />


    </form>
</body>
</html>

How to Preview Image Before uploading using javascript in asp.net

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
    $("#filePhoto").change(function () {
        readURL(this);
    });
   </script>

HTML as

Upload Photo:    <asp:FileUpload ID="FileUpload1" runat="server" onchange="readURL(this)" />
<img id="blah" src="#" alt="" style="height:150px; width:150px;"/>

How to save images into SQL Server

protected void btnSave_Click(object sender, EventArgs e)
        {
       
//Here convert image into bytes
            Stream fs = FileUpload1.PostedFile.InputStream;

            BinaryReader br = new BinaryReader(fs);

            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

//Now you need to add this byte into your Query.

        }

Mostly used and essential jQuery code examples

http://jquerybyexample.blogspot.com/2010/12/disable-cut-copy-and-paste-function-for.html

How to Disable right click using jQuery

You can find many java script code snippets to disable right click. But jQuery makes our life easy. Below jQuery code disables the right click of mouse.
1$(document).ready(function(){
2    $(document).bind("contextmenu",function(e){
3        return false;
4    });
5});        


We just need to bind the contextmenu event with the document element.

Method 2 (Send from one of the reader):

1$(document).ready(function(){
2    $(document).bind("contextmenu",function(e){
3        e.preventDefault();
4    });
5});                                                                         

Enable or Disable controls using jQuery in asp.net

You must have come across a situation where you have to make any element disable or enable.There are couple of ways using them you can enable/disable any element using jquery. jQuery really makes your task very easy. In below given example, I have disabled a textbox with id "txtName".

Approach 1
1$("#txtName").attr("disabled", true);
Approach 2
1$("#txtName").attr("disabled", "disabled");
If you wish to enable any element then you just have to do opposite of what you did to make it disable. However jQuery provides another way to remove any attribute.

Approach 1
1$("#txtName").attr("disabled", false);
Approach 2
1$("#txtName").attr("disabled", "");
Approach 3
1$("#txtName").removeAttr("disabled");
That's is. This is how you enable or disable any element using jQuery.

How to Use jQuery in ASP.NET

Using jQuery with ASP.NET

As this post is about "using jQuery with ASP.NET" so we will not be looking into "What is jQuery" and "How to use jQuery" assuming you know basics of jQuery. If not, then please read "Learn how to use jQuery?"

To begin with using jQuery with ASP.NET, first download the latest version the jQuery library from jQuery website and unzip or copy the file in your project or Visual studio solution. Microsoft Visual studio 2010 and 2012 include jQuery by default and provide intellisense to use jQuery. Assuming that you have placed the library in Script folder, add this in the head of your ASP.NET page (simple or master). (Its a good practice to keep your all js file under Script folder).
1<script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
Or you can directly refer them using various CDNs. Put this line of code in head section of ASP.NET Page.
1<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
In the above code, I have not used "http" protocol while referencing jQuery from Google CDN. Its not a mistake rather always use protocol less URL for referencing jQuery.

After this setup, you can use jQuery in your ASP.NET page. Let's see a demo.

Show alert window on click of ASP.NET Button.

Assuming a ASP.NET button with ID "btnSubmit " is placed on the page.
1<asp:Button ID="btnSubmit" runat="server" Text="Button" />
And now bind the click event to ASP.NET Button in document.ready section.
1<script type="text/javascript">
2  $(document).ready(function() {
3    $("#btnSubmit").click(function() {
4         alert("Alert using jQuery");
5    });
6  });
7</script>
In above jQuery code block, we have attached click event to the button using ID selectors. Read more about other jQuery selectors and how to use them.

Below is a list of useful jQuery code example for ASP.NET controls that we use on daily basis. One thing, while creating object of any ASP.NET control, always use ClientID. As when Master pages are used then the ID of the ASP.NET controls is changed at run time. Read more here. But with ASP.NET 4.0, this is changed and now you have control over the Client ID using ClientIDMode property.

Get label value:
1$('#<%=Label1.ClientID%>').text();
Set label value:
1$('#<%=Label1.ClientID%>').text("New Value");
Get Textbox value:
1$('#<%=TextBox1.ClientID%>').val();
Set Textbox value:
1$('#<%=TextBox1.ClientID%>').val("New Value");
Get Dropdown value:
1$('#<%=DropDownList1.ClientID%>').val();
Set Dropdown value:
1$('#<%=DropDownList1.ClientID%>').val("New Value");
Get text of selected item in dropdown:
1$('#<%=DropDownList1.ClientID%> option:selected').text();
Get Checkbox Status:
1$('#<%=CheckBox1.ClientID%>').attr('checked');
Check the Checkbox:
1$('#<%=CheckBox1.ClientID%>').attr('checked',true);
Uncheck the Checkbox:
1$('#<%=CheckBox1.ClientID%>').attr('checked',false);
Get Radiobutton Status:
1$('#<%=RadioButton1.ClientID%>').attr('checked');
Check the RadioButton:
1$('#<%=RadioButton1.ClientID%>').attr('checked',true);
Uncheck the RadioButton:
1$('#<%=RadioButton1.ClientID%>').attr('checked',false);
Disable any control:
1$('#<%=TextBox1.ClientID%>').attr('disabled', true);
Enable any control:
1$('#<%=TextBox1.ClientID%>').attr('disabled', false);
Make textbox read only:
1$('#<%=TextBox1.ClientID%>').attr('readonly', 'readonly');