How to Load One page into another Page Using AngularJS

Hi,
  We can easily Load One page into another Page in AngularJS by Using ng-include.

Here I have created 4 Pages

  1. index.html
  2. HTMLPage1.htm
  3. HTMLPage2.htm
  4. HTMLPage3.htm

In index.html  Add the following code


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<body ng-app ng-init="myurl='HTMLPage1.htm'">

        <nav class="{{active}}" ng-click="$event.preventDefault()">
<a href="#" class="home" ng-click="active='Home';myurl='HTMLPage1.htm'">Home</a>
<a href="#" class="about" ng-click="active='about';myurl='HTMLPage2.htm'">About</a>
<a href="#" class="contact" ng-click="active='contact';myurl='HTMLPage3.htm'">Contact</a>
</nav>
<p ng-show="active">You chose <b>{{active}}</b></p>

         <div ng-include="myurl">
        </div>

</body>

Here I have declare myurl as a variable. ng-init is the initial page value for while loading.
when i have click my menu, i have define myurl value by using ng-click.

Then the ng-include div shows that content of myurl value.

How to Show data from Database using class with AngularJs

Hi,

Here is the full code to show data using AngularJs


In .aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" type="text/javascript"></script>
     <style>
        table, th, td
        {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
        }
        table th
        {
            background-color: #274257;
            color: #fff;
        }
        table tr:nth-child(odd)
        {
            background-color: #f1f1f1;
        }
        table tr:nth-child(even)
        {
            background-color: #ffffff;
        }
    </style>
    <script type="text/javascript">
     var app = angular.module("myApp", []);
     app.controller("csrControl", function ($scope, $http) {



         $scope.Showcustomer = function () {

             var httpreq = {
                 method: 'POST',
                 url: 'ajxExampleShow.aspx/GetCustomerList',
                 headers: {
                     'Content-Type': 'application/json; charset=utf-8',
                     'dataType': 'json'
                 },
                 data: {}
             }
             $http(httpreq).success(function (response) {
                 $scope.customerList = response.d;
             })
         };


         $scope.Delete = function (csrId) {
             alert(csrId);
             //your web method call here for delete

         };
         // this line called while page load
         $scope.Showcustomer();
     });
   
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div ng-app="myApp" ng-controller="csrControl">
        <table>
            <thead>
                <tr>
                    <th>
                        No
                    </th>
                    <th>
                        Customer Name
                    </th>
                    <th>
                        Address
                    </th>
                    <th>Action</th>
                </tr>
            </thead>
            <tr ng-repeat="csr in customerList">
                <td ng-bind="csr.Id">
                </td>
                <td ng-bind="csr.Name">
                </td>
                <td ng-bind="csr.Address">
                </td>
                <td>
                    <a href="#" ng-click="Delete(csr.Id)">Delete</a>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>


In .aspx.cs

[System.Web.Services.WebMethod()]
        public static List<Customer> GetCustomerList()
        {
            List<Customer> objlst = new List<Customer>();
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = "select * from tblCustomer";
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                    }
                }
            }
            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    Customer obj = new Customer();
                    obj.Id = int.Parse(dr["Id"].ToString());
                    obj.Name = dr["Name"].ToString();
                    obj.Address = dr["Address"].ToString();

                    objlst.Add(obj);
                }
                   
            }
            return objlst;

        }



Here is the Customer Class

  public class Customer
    {
        private int _Id;
        public int Id
        {
            get { return _Id; }
            set { _Id = value; }
        }
        private String _Name;
        public String Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
        private String _Address;
        public String Address
        {
            get { return _Address; }
            set { _Address = value; }
        }
    }


SQL table Script For you

CREATE TABLE [dbo].[tblCustomer](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Address] [varchar](500) NULL,
 CONSTRAINT [PK_tblCustomer] 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]

How to save Data Using Class with angularJs.


Hi,

I am having Customer Class

public class Customer
{
    private int _Id;
    public int Id
    {
        get { return _Id; }
        set { _Id = value; }
    }
    private String _Name;
    public String Name
    {   
        get { return _Name; }
        set { _Name = value; }
    }
    private String _Address;
    public String Address
    {
        get { return _Address; }
        set { _Address = value; }
    }      
}
SQL Script For you

CREATE TABLE [dbo].[tblCustomer](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Address] [varchar](500) NULL,
 CONSTRAINT [PK_tblCustomer] 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]

Now, you have Customer Class and then Customer table in your database

Next, you have create a aspx page called ajsExample.aspx

Instead of that you have create a basic layout of angularjs

You have place CDN of AJS inside the header tag

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" type="text/javascript"></script>


In body you need initialize AJS  Structure

<div ng-app="myApp" ng-controller="csrControl">

</div>

ng-app - stands for my app name
ng-controller - stands for my controller name

Next you have create html controls for inputs

  <table>
                <tr>
                    <td>
                        Name
                    </td>
                    <td>
                        :
                    </td>
                    <td>
                        <input id="txtName" type="text" ng-model="csrName" />
                    </td>
                </tr>
                <tr>
                    <td>
                        Address
                    </td>
                    <td>
                        :
                    </td>
                    <td>
                        <input id="txtAddress" type="text" ng-model="csrAddress" />
                    </td>
                </tr>
                <tr>
                    <td colspan="3" align="right">
                        <input id="Button1" type="button" value="Save" ng-click="Save()" />
                    </td>
                </tr>
            </table>

So the basic html markup over here.

Next we are moving into web method

Use : using System.Data.SqlClient;


[System.Web.Services.WebMethod()]
        public static void SaveCustomer(Customer objcsr)
        {
            using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = "INSERT INTO tblCustomer (Name,Address) VALUES (@Name,@Address)";
                    cmd.Parameters.AddWithValue("@Name", objcsr.Name);
                    cmd.Parameters.AddWithValue("@Address", objcsr.Address);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

Next going to AngularJs

1. Create module for my application
2. Initialize controller
3. write ng-click function



 <script type="text/javascript">
     var app = angular.module("myApp", []);
     app.controller("csrControl", function ($scope, $http) {
     $scope.Save = function () {
                var objcsr = {
                    "Name": $scope.csrName,
                    "Address": $scope.csrAddress
                };
               
                var httpreq = {
                    method: 'POST',
                    url: 'ajsExample.aspx/SaveCustomer',
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8',
                        'dataType': 'json'
                    },
                    data: { objcsr }
                }
                $http(httpreq).success(function (response) {
                    alert("Saved successfully.");

                    //Here Clear textbox data
                    $scope.csrName = "";
                    $scope.csrAddress = "";
                })
            };
     });
    </script>



Here is the Full Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Hi</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"
        type="text/javascript"></script>
    <script type="text/javascript">
     var app = angular.module("myApp", []);
     app.controller("csrControl", function ($scope, $http) {
     $scope.Save = function () {
                var objcsr = {
                    "Name": $scope.csrName,
                    "Address": $scope.csrAddress
                };
               
                var httpreq = {
                    method: 'POST',
                    url: 'ajsExample.aspx/SaveCustomer',
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8',
                        'dataType': 'json'
                    },
                    data: { objcsr }
                }
                $http(httpreq).success(function (response) {
                    alert("Saved successfully.");
                    $scope.csrName = "";
                    $scope.csrAddress = "";
                })
            };
     });
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div ng-app="myApp" ng-controller="csrControl">
            <table>
                <tr>
                    <td>
                        Name
                    </td>
                    <td>
                        :
                    </td>
                    <td>
                        <input id="txtName" type="text" ng-model="csrName" />
                    </td>
                </tr>
                <tr>
                    <td>
                        Address
                    </td>
                    <td>
                        :
                    </td>
                    <td>
                        <input id="txtAddress" type="text" ng-model="csrAddress" />
                    </td>
                </tr>
                <tr>
                    <td colspan="3" align="right">
                        <input id="Button1" type="button" value="Save" ng-click="Save()" />
                    </td>
                </tr>
            </table>
        </div>
    </div>
    <p>
    </p>
    </form>
</body>
</html>

Overview about AngularJs


AngularJS History

AngularJS version 1.0 was released in 2012.
Miško Hevery, a Google employee, started to work with AngularJS in 2009.
The idea turned out very well, and the project is now officially supported by Google.

What is AngularJS?
AngularJS is a JavaScript framework. It is a library written in JavaScript. you have access it from here
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" type="text/javascript"></script>


Basic AngularJS directives

Actually the directive starts with data-ng,  but You can use ng-, instead of data-ng, the html gets understand this is AngularJS  directives.  some of directives are listed below
  1. ng-app
  2. ng-init
  3. ng-model
  4. ng-bind
  5. Expressions
  6. Module
  7. ng-controller
  8. ng-repeat
  9. ng-click

  1. ng-app
    • In c language the program starts with void main(). Like as AngularJS  identify our program starts with here. So the ng-app directive initializes an AngularJS application. 

       2. ng-init

    • The ng-init directive initializes application data. (i.e) the default value of our HTML controls (input, select, textarea).

       3. ng-model

    • The ng-model directive binds the value of HTML controls (input, select, textarea) to application data. (i.e) like act as a temporary storage memory. 

        4. ng-bind

    • The ng-bind directive binds application data to the HTML view. (i.e) shows data from temporary storage memory.  So here keep that same Address (value) of ng-model. (i.e) ng-model and ng-bind are twins.

         5. Expressions

    • AngularJS expressions can be written inside double braces: {{ expression }}. It can also be written inside a directive: ng-bind="expression". It contains literals, operators, and variables and also perform actions.
    • For Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
    • <input style="background-color:{{ClrName}}" ng-model="ClrName" value="{{ClrName}}">

         6. Module

    • The module is a splitter of an our application. We can split our whole complicated application into little bit of units by using this Module
    • Controllers always belong to a module.
    • For example <script>  var app = angular.module("myApp", []);  </script>
    • here myApp defines for ng-app 

         7. ng-controller

    • We can access the Variable values and user defined function by using this controller. Controllers always belong to a module. for Example
              <Script>

                 var app = angular.module("myApp", []);

                 app.controller("myCntrl", function ($scope, $http) {

                           $scope.Show = function () {

                                  alert($scope.Name);
                            };
                  });
               </Script>

             <div ng-app="myApp" ng-controller="myCntrl">
                  <input type="text" id="Name" ng-model="Name" />
                  <input type="button" value="Show" ng-click="Show()" />
            </div>

      8. ng-click


    • It's like as onclick or onclientclick in asp.net. you can use javascript function name within this ng-click
    • for example  <input type="button" value="Show" ng-click="Show()" />

How to Save, Retrieve and Delete data from Database using AngularJs with asp.net

Hi

First You should add this cdn in your header

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" type="text/javascript"></script>

In .aspx


<!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></title>
    <style>
        table, th, td
        {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
        }
        table th
        {
            background-color: #274257;
            color: #fff;
        }
        table tr:nth-child(odd)
        {
            background-color: #f1f1f1;
        }
        table tr:nth-child(even)
        {
            background-color: #ffffff;
        }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var app = angular.module("myApp", []);
        app.controller("myCntrl", function ($scope, $http) {
            $scope.studentorder = "StudetnID";
            $scope.studetnName = "";
            $scope.Save = function () {
                var httpreq = {
                    method: 'POST',
                    url: 'ajs.aspx/Save',
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8',
                        'dataType': 'json'
                    },
                    data: { StudentName: $scope.studetnName }
                }
                $http(httpreq).success(function (response) {
                    $scope.fillList();
                    alert("Saved successfully.");
                })
            };
            $scope.Delete = function (SID) {
                if (confirm("Are you sure want to delete?")) {
                    var httpreq = {
                        method: 'POST',
                        url: 'ajs.aspx/Delete',
                        headers: {
                            'Content-Type': 'application/json; charset=utf-8',
                            'dataType': 'json'
                        },
                        data: { StudentID: SID }
                    }
                    $http(httpreq).success(function (response) {
                        $scope.fillList();
                        alert("Deleted successfully.");
                    })
                }
            };
            $scope.fillList = function () {
                $scope.studetnName = "";
                var httpreq = {
                    method: 'POST',
                    url: 'ajs.aspx/GetList',
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8',
                        'dataType': 'json'
                    },
                    data: {}
                }
                $http(httpreq).success(function (response) {
                    $scope.StudentList = response.d;
                })
            };
            $scope.fillList();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div ng-app="myApp" ng-controller="myCntrl">
        <table>
            <tr>
                <td>
                    Student Name :
                </td>
                <td>
                    <input type="text" id="txtStudentName" ng-model="studetnName" />
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="button" value="Save" ng-click="Save()" />
                </td>
            </tr>
        </table>
        <br />
        <br />
        <table>
            <thead>
                <tr>
                    <th>
                        StudentID
                    </th>
                    <th>
                        StudentName
                    </th>
                    <th>
                    Action
                    </th>
                </tr>
            </thead>
            <tr ng-repeat="student in StudentList | orderBy : studentorder ">
                <td ng-bind="student.StudentID">
                </td>
                <td ng-bind="student.StudentName">
                </td>
                <td>
                    <a href="#" ng-click="Delete(student.StudentID)">Delete</a>
                </td>
            </tr>
        </table>
    </div>
   
    </form>
</body>
</html>




In aspx.cs

         [System.Web.Services.WebMethod()]
        public static void Save(string StudentName)
        {
            using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = "insert into tblStudents (StudentName) values (@StudentName);";
                    cmd.Parameters.AddWithValue("@StudentName", StudentName);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

        [System.Web.Services.WebMethod()]
        public static void Delete(int StudentID)
        {
            using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = "update tblStudents set IsActive=0 where StudentID=@StudentID;";
                    cmd.Parameters.AddWithValue("@StudentID", StudentID);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }

        [System.Web.Services.WebMethod()]
        public static List<Names> GetList()
        {
            List<Names> names = new List<Names>();
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = "select StudentID,StudentName from tblStudents where IsActive=1;";
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                    }
                }
            }
            if (ds != null && ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                    names.Add(new Names(int.Parse(dr["StudentID"].ToString()), dr["StudentName"].ToString()));
            }
            return names;
        }

    }
}


Add Another class


    public class Names
    {
        public int StudentID;
        public string StudentName;
        public Names(int _StudentID, string _StudentName)
        {
            StudentID = _StudentID;
            StudentName = _StudentName;
        }



Table

CREATE TABLE [dbo].[tblStudents](
    [StudentID] [int] IDENTITY(1,1) NOT NULL,
    [StudentName] [varchar](50) NOT NULL,
    [IsActive] [bit] NOT NULL CONSTRAINT [DF_tblStudents_IsActive]  DEFAULT ((1)),
 CONSTRAINT [PK_tblStudents] PRIMARY KEY CLUSTERED
(
    [StudentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

How to Create Auto Complete Textbox using Asp.net with Jquery

In aspx

<script type="text/javascript">
        $(function () {
            $("#<%=txtArea.ClientID%>").autocomplete({
                source: function (request, response) {
                    var area = $('[id$=txtArea]').val();
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "AreaWiseReport.aspx/GetAutoCompleteDataByArea",
                        data: "{'area':'" + area + "'}",
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Check No");
                        }
                    });
                }
            });
        });
 
    </script>

In aspx.cs

[WebMethod]
        public static List<string> GetAutoCompleteDataByRegNo(string area)
        {
            List<string> result = new List<string>();
            using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("select DISTINCT AreaName from Mater_Area where AreaName LIKE '%'+@SearchText+'%'", con))
                {
                    con.Open();
                    cmd.Parameters.AddWithValue("@SearchText", AreaName);
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        result.Add(dr["AreaName"].ToString());
                    }
                    return result;
                }
            }
        }



Here Replace System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString  as  your Connection String

AreaName  as your column Name, which column you want to get autocomplete

Mater_Area as your Table Name

Add Jquery in your aspx

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">

How to Load Data in Jquery Datetime Picker from Database using Jquery

  var date = eval(data.d.JoinDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));

                    var dd = date.getDate();
                    var mm = date.getMonth() + 1;
                    var yyyy = date.getFullYear();
                    var jdt = dd + '-' + mm + '-' + yyyy;

                    $('[id$=txtJoinDate]').val(jdt);