Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Saturday 28 February 2015

Sometime it is needed to crop the uploaded in asp.net web application. This can be done by using jquery. In this article I will explain how to validate image type(extension) , upload image through asp.net fileupload control and then crop the image using jQuery plugin and save cropped image to folder.

This is mostly required in our application to hide content on the basis of some condition i.e. on radiobutton list or check box. I have explained the example of check box in my previous article.
In this article I will explain how to Show & Hide controls or  DIV on RadioButtonList selection in asp.net using jQuery.
Example:  In this example user has to select the Nationality i.e. Indian or Others. If user selects the option of “others”, then user has to enter details like country and city. No information is needed in case of “Indian” option. So in case of “Others” we can make the textbioxes to enter Country name and city name to appear and disappear at run time by placing them in DIV tag and using jQuery we can hide or unhide the DIV according to the RadioButtonList selected item.
Source Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
   <script src="//code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#<%=rblPaymentMode.ClientID %>').click(function () {
                var SelectedValue = $('#<%=rblPaymentMode.ClientID %> input[type=radio]:checked').val();

                if (SelectedValue == 1) {
                    //If cash is selected then hide the Div
                    $('#dvShowHide').css("display", "none");
                    //or you can simply use jQuery hide method to hide the Div as below:
                    //$('#dvShowHide').hide();         
                }
                else {
                    //If Cheque is selected then show the Div
                    $('#dvShowHide').css("display", "block");
                    //or you can simply use jQuery show method to show the Div as below:
                    //$('#dvShowHide').show();
                    //Clear textboxes
                    $('#<%=txtBankName.ClientID %>').val('');
                    $('#<%=txtChequeNumber.ClientID %>').val('');
                    //Set focus in bank name textbox
                    $('#<%=txtBankName.ClientID %>').focus();
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 370px;">
            <legend><strong>Show/Hide Div Content On RadioButton Check</strong></legend>
            <br />
            <strong>Nationality</strong>
            <br />
            <br />
            <asp:RadioButtonList ID="rblPaymentMode" runat="server" RepeatDirection="Horizontal">          
            <asp:ListItem Text="Indian" Value="1"></asp:ListItem>
            <asp:ListItem Text="Others" Value="2"></asp:ListItem>
            </asp:RadioButtonList>
            <br />
           <div id="dvShowHide" style="display:none;">
                Country :&nbsp;&nbsp; <asp:TextBox ID="txtBankName" runat="server"></asp:TextBox><br />
                City: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:TextBox ID="txtChequeNumber" runat="server"></asp:TextBox>
            </div>
        </fieldset>
    </div>
    </form>
</body>


</html>
In this article I will explain how to use jQuery function to set maximum allowed characters and also count and display number of remaining characters in multiline textbox (TextArea) or simple textbox or we can say prevent/avoid/limit the numbers of characters to be entered in the textbox. 

Introduction: In this article I will explain with simple example how to use ajax method of jquery in asp.net to call Web-Method to avoid page post back (without reloading/refreshing page).

Friday 27 February 2015

In this article I will explain how to get running sum of all the asp.net textbox values using jQuery and display in Label or Textbox control.

Sometime it is required to get running total of textbox values. This can be done by using server side code in asp.net or Using Jquery. 

One of the common requirement while working on asp.net projects is to show, hide the contents or controls placed inside Div on CheckBox select/unselect. This can be done through code in asp.net or by using jQuery. jQuery option is easy and better, because jQuery is fast as compare to .NET server side code.

One of the common requirement while working on asp.net projects is to show, hide the contents or controls placed inside Div on CheckBox select/unselect. This can be done through code in asp.net or by using jQuery. jQuery option is easy and better, because jQuery is fast as compare to .NET server side code.

One of the common requirement while working on asp.net projects is to show, hide the contents or controls placed inside Div on CheckBox select/unselect. This can be done through code in asp.net or by using jQuery. jQuery option is easy and better, because jQuery is fast as compare to .NET server side code.

When we work work with dropdownlist its sometime  required to get dropdownlist value, text or index at webpage. This can be done by doing some code at server side. For that we have dropdownlist attributes like "SelectedIndex" to get the selected item’s index, "SelectedValue" to get the selected item’s value and "SelectedItem.Text" to get selected item’s text. But to avoid code we can also do this job at client end by using jQuery.

We can validate and save data in database using jQuery, Ajax and Web-service method. jQuery ajax allows us to call server side ASP.NET page methods/functions declared as Web Method from client side without any postback. We make ajax call to web method using jQuery which contains the code to insert data in sql server.

In this article I am going to explain how to validate and save data into SQL SERVER database table in asp.net without any post back (asynchronously) using jQuery AJAX JSON and WebMethod.

Description:
Implementation: Let’s create a sample page to demonstrate the concept.
Create a datanbase in sql server  eg. “test”. Now create a table as given below:

CREATE TABLE [dbo].[Emp_Personal](
      [EmpPer_Id] [int] IDENTITY(1,1) NOT NULL,
      [EmpName] [varchar](100) NULL,
      [Age] [int] NULL,
      [Address] [varchar](500) NULL
) ON [PRIMARY]
In Web.config file create the connection string as: 
  <connectionStrings>
    <add name="EmpCon" connectionString="Data Source=localhost;Initial Catalog=test;Integrated Security=True"/>
  </connectionStrings>

Now create a stored procedure to save Employee Personal Details 

Create PROCEDURE [dbo].[SaveEmp_SP]
                @EmpName  VARCHAR(100),
              
                @age   INT,
                @Address  VARCHAR(500)
AS
BEGIN
                INSERT INTO dbo.Emp_Personal(EmpName,Age,Address)
                VALUES(@EmpName,@age,@Address)
END

Source Code:
Design Section:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">

        function SaveRecord() {
            //Get control's values
            var Name = $.trim($('#<%=txtName.ClientID %>').val());
            var age = $.trim($('#<%=txtAge.ClientID %>').val());
            var Address = $.trim($('#<%=txtAddress.ClientID %>').val());

            var msg = "";
            //check for validation
            if (Name == '') {
                msg += "<li>Please enter Employee name</li>";
            }
            if (age == '') {
                msg += "<li>Please enter Age</li>";
            }
            if (Address == 0) {
                msg += "<li>Please enter address</li>";
            }
            
            if (msg.length == 0) {
                //Jquery ajax call to server side method
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    //Url is the path of our web method (Page name/function name)
                    url: "MyPageName.aspx/SaveBookDetails",
                    //Pass paramenters to the server side function
                    data: "{'EmpName':'" +Name+ "', 'Age':'" +age+ "','Address':'" +Address+ "'}",
                    success: function (response) {
                        //Success or failure message e.g. Record saved or not saved successfully
                        if (response.d == true) {
                            //Set message
                            $('#dvResult').text("Record saved successfully");
                            //Reset controls                         
                            $('#txtName').val('');
                            $('#txtAge').val('');
                            $('#txtAddress').val("0");
                        }
                        else {
                            $('#dvResult').text("Record could't be saved");
                        }
                        //Fade Out to disappear message after 6 seconds
                        $('#dvResult').fadeOut(6000);
                    },
                    error: function (xhr, textStatus, error) {
                        //Show error message(if occured)
                        $('#dvResult').text("Error: " + error);
                    }
                });
            }
            else {
                //Validation failure message
                $('#dvResult').html('');
                $('#dvResult').html(msg);
            }
            $('#dvResult').fadeIn();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
    <td>Employee Name:</td>
    <td>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
    </tr>
 
    <tr>
    <td>Age:</td>
    <td>
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>      
    </tr>
  
    <tr>
    <td>Address:</td>
    <td>
        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
    </tr>
                <tr>
                    <td></td>
                    <td>
                        <button type="submit" onclick="SaveRecord();return false">Submit</button>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <div id="dvResult"></div>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>


Asp.Net C# Code to validate and store data in sql server database table using jQuery Ajax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;

public partial class Jquery_Insert : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static bool SaveEmpDetails(string Name, string age, Int32 Address)
    {
        bool status;

        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Empcon"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("SaveEmp_SP", con))
            {
               
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@EmpName",Name);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@Address", Address);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                Int32 retVal = cmd.ExecuteNonQuery();
                if (retVal > 0)
                {
                    status = true;
                }
                else
                {
                    status = false;
                }
                return status;
            }
        }
    }

}

Asp.Net VB Code to validate and store data in sql server database table using jQuery Ajax

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services

Partial Public Class Jquery_Insert
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    End Sub
    <WebMethod()> _
    Public Shared Function SaveEmpDetails(ByVal Name As String, ByVal age As String, ByVal Address As Int32) As Boolean
        Dim status As Boolean

        Imports (SqlConnection con = New SqlConnection(ConfigurationManager.ConnectionStrings("Empcon").ConnectionString))
        {
            Imports (SqlCommand cmd = New SqlCommand("SaveEmp_SP", con))
            {

        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@EmpName", Name)
        cmd.Parameters.AddWithValue("@age", age)
        cmd.Parameters.AddWithValue("@Address", Address)
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If
        Dim retVal As Int32 = cmd.ExecuteNonQuery()
        If retVal > 0 Then
            status = True
        Else
            status = False
        End If
        Return status
            }
        }
    End Function


End Class