May 2016 ~ MiTechDev.com

Wednesday, 25 May 2016

How to implement Cascading Dropdownlist with Angular JS in ASP.NET MVC 5

22:23:00 Posted by raviteja swayampu , 2 comments
In this post i would like to explain about How to implement Cascading Dropdown list using Angular JS in ASP.NET MVC 5 application.Thank you for comments and feedback for previous post How to create Registration page using Angular JS.your encouragement makes me feel proud to be blogger.Your feedback helps me to create more quality articles. If you are new to angular JS check the basics click here i have explained briefly about angular js here.

Description:

Sometimes we need to create a drop down lists where populated values depends on the previous drop down selected values these are called Cascading drop down lists.You can see these types of drop down lists in many of the web applications.For example States drop down populated based on the country we selected(In this article i am creating same Country-State cascading drop down).
Now lets see How we are going to implement Cascading Drop down list using Angular js in ASP.NET application.
The application UI is look like this....

cascading dropdown using angular js in mvc5

Steps:

Step 1: Creating Tables for Dropdown Data

1.Create Two tables in Database Country , States tables
2.I created two tables with below columns.


cascading dropdown list in angularjs states table

Step 2: Add ADO.NET Entity Data Model

1.Right click on Solution--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.

Step 3: Add Action Methods to Get Country,States data

1.Create Controller and name it as HomeController and add below action methods to get data from the database and to send data to angular controller ($http service get data from this action method).
2.GetCountries() : Fetch country values.
3.GetStates() : Fetch States values.
4.Replace below code in Home Controller.
// get country list from DB
        public ActionResult GetCountries()
        {
            List countrylist = new List();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                countrylist = dc.Countries.OrderBy(a => a.CountryName).ToList();
            }
            return new JsonResult { Data = countrylist, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        // Get States based on Country selected in dropdown

        public ActionResult GetStates(int countryID)
        {
            List statelist = new List();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                statelist = dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
            }
            return new JsonResult { Data = statelist, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

Step 4: Add new script files for Angular Module & Controller

1.Right click on Scripts folder and add new java script file for angular module creation.
(function () {
    //Create a Angular Module 
    var app = angular.module('MyApp', []);  
    //name of angular application is 'MyApp'
})();

2.Now attach or extend this angular module by creating angular controller.
3.Here i named it as "DropdownController".
4.Add below code in DropdownController,js files.
angular.module('MyApp').controller('DropdownController', function ($scope,StateService) {
    //create a angular controller  
    // expained about controller in Part2 // Here LocationService (Service) Injected

    $scope.CountryID = null;
    $scope.StateID = null;
    $scope.CountryList = null;
    $scope.StateList = null;

    $scope.StateTextToShow = "Select State";
    $scope.Result = "";

    // Populate Country list using GetCountry()
    StateService.GetCountry().then(function (d) {
        //assign countries to $scope.CountryList
        $scope.CountryList = d.data;    //success
    },
    function (error) {
        alert('Error!');    //throws error for failure
    });
    // This function to Populate State 
    // it is called after selecting country from dropdownlist
    $scope.GetState = function () {
        $scope.StateID = null; // Clear Selected State if any
        $scope.StateList = null; // Clear previously loaded state list
        $scope.StateTextToShow = "Please Wait..."; // this will show until load states from database

        //Load State 
        StateService.GetState($scope.CountryID).then(function (d) {
            $scope.StateList = d.data;
            $scope.StateTextToShow = "Select State";
        }, function (error) {
            alert('Error!');
        });

    }
    // Function for show result
    //it will be displayed after clicking on button
    $scope.ShowResult = function () {
        $scope.Result = "Selected Country ID : " + $scope.CountryID + " State ID : " + $scope.StateID;
    }

})
.factory('StateService', function ($http) { //factory methos to get data from server.
    var fac = {};
    fac.GetCountry = function () {
        return $http.get('/Home/GetCountries')
    }
    fac.GetState = function (countryID) {
        return $http.get('/Home/GetStates?countryID='+countryID)
    }

    return fac;
});

5.Here in above code i created a angular service StateService to get data from remote server through ajax calls.
6.ShowResult function returns the selected values in two drop down lists and displays in a modal popup created by using Bootstrap responsive framework.
Note : Here i explained  How to integrate and use Bootstrap framework in ASP.NET MVC5 application.

Step 5: Add Index View to display Dropdown lists

1.Create Index Actin Method in HomeController.
// GET: /Home/        
        public ActionResult Index()
        {
            return View();
        }

2.Add View to Index action method and replace code with following code.
@{
    ViewBag.Title = "Cascading Dropdown using AngularJS and MVC5";
}
<style>
    body{
        margin-top:50px;
        margin-left:30px;
        margin-right:400px;
    }
</style>
<div class="panel panel-info">
    <div class="panel-heading">
        Cascading Dropdown using AngularJS and MVC5
    </div>
    <div class="panel-body">
        <div ng-controller="DropdownController">
            <div class="dropdown">
                Country :
                <select class="btn btn-primary dropdown-toggle" ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetState()">
                    <option value="">Select Country</option>
                </select>

                State :
                <select class="btn btn-primary dropdown-toggle" ng-model="StateID" ng-options="I.StateID as I.StateName for I in StateList">
                    <option value="">{{StateTextToShow}}</option>
                </select>

                <input class="btn btn-success" type="button" value="Get Selected Values" ng-click="ShowResult()" data-toggle="modal" data-target="#myModal" />

                <div class="modal fade" id="myModal" role="dialog">
                    <div class="modal-dialog">

                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                <h4 class="modal-title">Modal Header</h4>
                            </div>
                            <div class="modal-body" id="myModal">
                                {{Result}}
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

         </div>
     </div>
    <div class="panel-footer">
        Microsoft tech Developments 2016
    </div>
</div>
@section scripts{ 
<script src="~/Scripts/DropdownController.js"></script>
}
ng-options: Here ,i used ng-options directive to repeat the elements in CountyList . We can do this using ng-repeat directive and in any cases it is easy to implement also. but, using ngOptions is more flexible campared to ngRepeat.

ng-change: ngChange directive triggers an event time Element is changed.

3.Add Scripts references in Index.cshtml page like below(I added Myapp.js file reference in Layout page for angular module)
@section scripts{  
<script src="~/Scripts/DropdownController.js"></script>
}

Modify _Layout page with below modifications.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
    @* Here  ng-app="MyApp" is used for auto-bootstrap an AngularJS application(it create angular application). here ng-app="MyApp" means <body> element is the owner 
    of AngularJS application*@
<body ng-app="MyApp">      
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    <script src="~/Scripts/bootstrap.js"></script>
    @* Add Angular Library Here *@
    @Scripts.Render("~/bundles/angular")
    <script src="~/Scripts/MyApp.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>
Now run the application Press F5
we will get the selected values in modal popup like below screen shot.

cascading dropdown list in angularjs

You may also like below

Download source code this application Here.

Conclusion:
I hope this article is understandable for every reader.Please recommend if you want to improve the readability of this article through comments.If you are not subscribed to this site please subscribe...


Tuesday, 24 May 2016

How to create a Registration form using Angular JS in ASP.NET MVC 5

00:47:00 Posted by raviteja swayampu , , 2 comments
In this tutorial i am going to explain about How to Create simple Registration page using Angular js in MVC 5 application with angular validation.We have learned how to get data from database using angular with help of services.In this tutorial we are using services to save the data in database.
please refer  the below posts for understanding of angular.

Note: I have explained basics of angular js please refer previous posts to understand the basics if you do not know basics. 

The expected outcome for this application is this ...
Registration page using angular js in asp.net mvc5
Registration page using Angular JS

In this application we are using another service $q .Which is an angular service which helps us to run asynchronous function and returns result when the processing is done. 

Step 1: Create a Data table in Database

1.Right click server explorer --> expand Database --> Right click on tables --> Click Add new table.
2.Create a table with  following columns if you want you can add more columns.
3.Here i created following table.

Step 2: Add ADO.NET Entity Data Model

1.Right click on Solution--> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.

Step 3: Add New Action Method to save user data in database

1.Add below action method in HomeController to save data which is come from angular controller and saves that in database.
2.Replace the code with following code.
//Registration form saving code
        [HttpPost]
        public JsonResult Register(User u)
        {
            string message = "";          
            if (ModelState.IsValid)
            {
                using (MyDatabaseEntities dc = new MyDatabaseEntities())
                {
                    //check username available
                    var user = dc.Users.Where(a => a.Username.Equals(u.Username)).FirstOrDefault();
                    if (user == null)
                    {                      
                        dc.Users.Add(u);
                        dc.SaveChanges();
                        message = "Success";
                    }
                    else
                    {
                        message = "Username not available!";
                    }
                }
            }
            else
            {
                message = "Failed!";
            }
            return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

Step 4: Add new js file to create angular Controller

1.Before creating angular controller we need to create angular application module.js file.
(function () {
    var myApp = angular.module("myApp",[]);
})();
2.Now create Registration controller --Right click on Scripts folder and add RegistrationController.js
3.Replace the code with below js code.
angular.module('MyApp') 
.controller('RegistationController', function ($scope, RegistrationService) {
    //Default Variable
    $scope.submitText = "Save";
    $scope.submitted = false;
    $scope.message = '';
    $scope.isFormValid = false;
    $scope.User = {
        Username : '',
        Password: '',
        FullName: '',
        EmailID: '',
        Gender:''
    };
    //validates form on client side
    $scope.$watch('f1.$valid', function (newValue) {
        $scope.isFormValid = newValue;
    });
    //Save Data
    $scope.SaveData = function (data) {
        if ($scope.submitText == 'Save')
        {
            $scope.submitted = true;
            $scope.message = '';

            if ($scope.isFormValid)
            {
                $scope.submitText = 'Please Wait...';
                $scope.User = data;
                RegistrationService.SaveFormData($scope.User).then(function (d) {
                    alert(d);
                    if (d == 'Success') {
                        //have to clear form here
                        ClearForm();
                    }
                    $scope.submitText = "Save";
                });
            }
            else {
                $scope.message = '';
            }
        }
    }
    //Clear Form 
    function ClearForm() {
        $scope.User = {};
        $scope.f1.$setPristine(); //here f1 is form name
        $scope.submitted = false;
    }
})
.factory('RegistrationService', function ($http, $q) { 
    
    var fac = {};
    fac.SaveFormData = function (data) {
        var defer = $q.defer();
        $http({
            url: '/Home/Register',
            method: 'POST',
            data: JSON.stringify(data),
            headers: {'content-type' : 'application/json'}
        }).success(function (d) {
            // Success callback
            defer.resolve(d);
        }).error(function (e) {
            //Failed Callback
            alert('Error!');
            defer.reject(e);
        });
        return defer.promise;
    }
    return fac;
});

Step 6: Add View to display Registration Form

1.Right click on Index action --> Add View --> add
2.Replace Index.cshtml view code with following code.

@{
    ViewBag.Title = "Registration page using Angular";
}
<style>
    body{
        margin-top:50px;
    }
    input {
        max-width:300px;
    }
    .error {
        color: red;
    }

</style>

<div class="panel panel-info" style="margin-left:30px;margin-right:500px;">
    <div class="panel-heading">
        Sample Registration Form using Angular
    </div>
    <div ng-controller="RegistationController" class="panel-body">
        <form novalidate name="f1" ng-submit="SaveData(User)" class="form-horizontal">
            <div class="form-group">
                <label class="text text-info col-md-offset-2">Full Name : </label>
                <input type="text" ng-model="User.FullName" class="form-control col-md-offset-2" name="uFullName" ng-class="submitted?'ng-dirty':''" required autofocus />
                <span class="error col-md-offset-2" ng-show="(f1.uFullName.$dirty || submitted) && f1.uFullName.$error.required">Fullname required!</span>
            </div>

            <div class="form-group">
                <label class="text text-info col-md-offset-2">Email ID : </label>
                <input type="email" ng-model="User.EmailID" class="form-control col-md-offset-2" name="uEmailID" ng-class="submitted?'ng-dirty':''" />
                <span class="error col-md-offset-2" ng-show="(f1.uEmailID.$dirty || submitted) && f1.uEmailID.$error.required">Email required</span>
                <span class="error col-md-offset-2" ng-show="(f1.uEmailID.$dirty || submitted) && f1.uEmailID.$error.email">Email ID not valid!</span>
            </div>
            <div class="form-group">
                <label class="text text-info col-md-offset-2">Username : </label>
                <input type="text" ng-model="User.Username" class="form-control col-md-offset-2" name="uUsername" ng-class="submitted?'ng-dirty':''" required />
                <span class="error col-md-offset-2" ng-show="(f1.uUsername.$dirty || submitted) && f1.uUsername.$error.required">Username required!</span>
            </div>
            <div class="form-group">
                <label class="text text-info col-md-offset-2">Password : </label>
                <input type="password" ng-model="User.Password" class="form-control col-md-offset-2" name="uPassword" ng-class="submitted?'ng-dirty':''" required />
                <span class="error col-md-offset-2" ng-show="(f1.uPassword.$dirty || submitted) && f1.uPassword.$error.required">Password required!</span>
            </div>
            <div class="form-group">
                <label class="text text-info col-md-offset-2"> Gender : </label>
                <input type="radio" class="col-md-offset-2" ng-model="User.Gender" name="uGender" value="Male" required /> Male
                <input type="radio" class="col-md-offset-2" ng-model="User.Gender" name="uGender" value="Female" required /> Female
                <span class="error" ng-show="(f1.uGender.$dirty || submitted) && f1.uGender.$error.required">Gender required!</span>

            </div>
            <div class="form-group">
                <label></label>
                <input type="submit" class="btn btn-success col-md-offset-2" value="{{submitText}}" />
            </div>
        </form>
    </div>
    <div class="panel-footer">
        Mitechdev application
    </div>
</div> 

@section Scripts{
<script src="~/Scripts/RegistrationController.js"></script>
}

3.Add script reference at the end of Index.cshtml page.
4.For above code we applied Bootstrap styles to beautify form.
5.I used same validation i explained in previous post.

Now run the application and insert some records into form and submit it.
you can see what i  inserted here.

inserted records in table using angular form
inserted records in form









The validation for this form works like below screen shot.

angular form validation in mvc5
Angular form validation
Download source code from here Download

Conclusion:
I hope this tutorial is understandable for every reader.If you recommend any modifications to this site please specify in form of comments to improve the quality of this post.
For daily updates please follow this site through Email or Social networks....


Monday, 16 May 2016

how to get and display table data from database using angular in MVC application

05:52:00 Posted by raviteja swayampu , 2 comments
Hi every one in this post i would like to explain about How to get and display table data from database using angular JS.Till now we learned about how to get data from database using angular.Now we are going to learn How work with tabular data in this tutorial.The final data is displayed in table like in below image.

Note: I have explained basics of angular js please refer previous posts to understand the basics if you do not know basics. 
displaying table data from database using angularjs

In this application we are going to use ng-repeat directive to iterate the table records.ngRepeat repeats the HTML elements.We use it to iterate collection values.

Step 1: Create a Data table in Database

1.Right click server explorer --> expand Database --> Right click on tables --> Click Add new table.
2.Create a table with  following columns if you want you can add more columns.
3.Here i created following table.

creating new table in visual studio

Step 2: Add ADO.NET Entity Data Model

1.Right click on Models --> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.

Step 3: Add New Action Method to get User Data from Database and send in the form of JsonResult

1.This Action Method fetch data from database and returns that data in Json format to angular Controller for processing.
2.Add getUsers() Action in HomeController.
public JsonResult getUsers()
        {
            List userlist = new List();
            using (DatabaseEntities db = new DatabaseEntities()) {
                userlist = db.Users.OrderBy(a=>a.FullName).ToList();
            }
            return new JsonResult { Data=userlist,JsonRequestBehavior=JsonRequestBehavior.AllowGet};
        }

Step 4: Add new js file to create angular Controller and Factory method

1.Create angular module in  Module.js file.
(function () {
    var myApp = angular.module("myApp",[]);
})();
2.Now add another script file to add angular Controller and Factory method to call data from server 3.Right click on Scripts folder --> add LoginController.js
4.Replace code with following code .
angular.module("myapplication").controller("TableController", function ($scope, UserService) {
    $scope.User = null;
    UserService.getUsers().then(function (d) {
        $scope.User = d.data; 
    },function(){
        alert("error occured try again");
    });
})
.factory("UserService", function ($http) {
    var fact = {};
    fact.getUsers = function () {
        return $http.get('/Home/getUsers');
    }
    return fact;
});
    
5.Factory: Here ,the factory method fetch data from server using $http call.

Step 6: Add View to display Login Form

1.Right click on Index action --> Add View --> add
2.Replace Index.cshtml view code with following code.

@{
    ViewBag.Title = "Display table using Angular JS";
}
<div class="panel panel-info">
    <div class="panel-heading">
        Displaying DB data using Angular in MVC5
    </div>
    <div ng-controller="TableController">
        <table class="table table-bordered table-responsive">
            <thead>
                <tr>
                    <th>
                        Full Name
                    </th>
                    <th>
                        Email
                    </th>
                    <th>
                        DOB
                    </th>
                    <th>
                        Phone
                    </th>
                    <th>
                        Address
                    </th>
                    <th>
                        Designation
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="i in User">
                    <td>{{i.FullName}}</td>
                    <td>{{i.Email}}</td>
                    <td>{{i.DOB.slice(6,-2)|date:'dd-MM-yyyy'}}</td>
                    <td>{{i.Phone}}</td>
                    <td>{{i.Address}}</td>
                    <td>{{i.Designation}}</td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="panel-footer">
        copyrighted by Mitechdev.com
    </div>
</div>
@section scripts{

<script src="~/Scripts/TableDisplayController.js"></script>

}

3.Add script reference at the end of Index.cshtml page.
4.Here in above code i used slice() function and also applied angular filter to filter the DOB column.

Filters: Filters are used to change, modify or formats the data to display to user.There are some predefined filter that angular provides Lowercase filter,Currency filter,OrderBy filter etc. are predefined filters in angular js.We can develop our own filters also based on requirement.

Syntax: {{expression | filter expression}} 
Ex: {{student.fullName() | uppercase}} // here we changing case to upper.

Download  source code for this tutorial Download

Conclusion:
I hope this tutorial is understandable for every reader.If you recommend any modifications to this site please specify in form of comments to improve the quality of this post.
For daily updates please follow this site.


Sunday, 15 May 2016

How to create a Login page using Angular JS in MVC5

22:17:00 Posted by raviteja swayampu , , 7 comments
Hi every one welcome again.Thank you for comments and feedback for the last post How to get data from database using angular JS in MVC 5.In this tutorial i am going to explain about how to create a login page using Angular js in MVC 5 application.The final outcome of tutorial is like this.


login page using angular in MVC5
Create Login page using Angular js in MVC 5

if you are new to angular please refer previous posts for basics of angular in MVC 5
In this tutorial i used Simple form validation using angular(we will discuss about angular validation in detail in future post).And also a $http angular built in service.

$http: It is a angular JS built in service for communicating with remote servers.In Angular all communications (Request and response) between server and client are handled by services like $http.

Step 1: Create a Data table in Database

1.Here i used Local Database for Table creation (Sql Express).
2.Right click server explorer --> expand Database --> Right click on tables --> Click Add new table.
3.Create a table with  following columns if you want you can add more columns.
4.Here i created following table.


Step 2: Add ADO.NET Entity Data Model

1.Right click on Models --> Add --> New Item -->Select ADO.NET Entity Data Model(Under Data) --> name it -->Add --> select Add from Database (In Entity Data Model wizard) --> Next
2.Select Database --> give name for web.config.
3.Choose your Database objects(tables) and click finish.

Step 3: Add a Model Class to Solution

1.Right click Models --> Add --> Class and name it (I named it as UserModel.cs).
2.These Model objects are useful while we sending data from View to Controller.
3.We bind this Model properties with angular ngModel.(you will see in index.cshtml).
4.replace code with following code
namespace LoginUsingAngular.Models
{
    public class UserModel
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }
}

Step 4: Add New Action Method in HomeController to Check User Data

1.This Action Method gets data from database based on user entered data in form.and returns that data in Json format to angular Controller.
2.Add code in HomeController
getLoginData():
public ActionResult getLoginData(UserModel obj)
        {
            DatabaseEntities db = new DatabaseEntities();
            var user = db.Users.Where(x => x.Email.Equals(obj.Email) && x.Password.Equals(obj.Password)).FirstOrDefault();
            return new JsonResult {Data=user,JsonRequestBehavior=JsonRequestBehavior.AllowGet };
        }

Step 5: Add angular controller for checking Login Form

1.Create angular module in  Module.js file.
(function () {
    var myApp = angular.module("myApp",[]);
})();
2.Now add another script file for angular controller and Factory method.
3.Right click on Scripts folder --> add LoginController.js
4.Replace code in LoginController.js file.
angular.module('myApp').controller('LoginController', function ($scope, LoginService) {

        //initilize user data object
        $scope.LoginData = {
            Email: '',
            Password:''
        }
        $scope.msg = "";
        $scope.Submited = false;
        $scope.IsLoggedIn = false;
        $scope.IsFormValid = false;

        //Check whether the form is valid or not using $watch
        $scope.$watch("myForm.$valid", function (TrueOrFalse) {
            $scope.IsFormValid = TrueOrFalse;   //returns true if form valid
        });

        $scope.LoginForm = function () {
            $scope.Submited = true;
            if ($scope.IsFormValid) {
                LoginService.getUserDetails($scope.UserModel).then(function (d) {
                    debugger;
                    if (d.data.Email != null) {
                        debugger;
                        $scope.IsLoggedIn = true;
                        $scope.msg = "You successfully Loggedin Mr/Ms " +d.data.FullName;
                    }
                    else {
                        alert("Invalid credentials buddy! try again");
                    }
                });
            }
        }
    })
    .factory("LoginService", function ($http) {
        //initilize factory object.
        var fact = {};
        fact.getUserDetails = function (d) {
            debugger;
            return $http({
                url: '/Home/getLoginData',
                method: 'POST',
                data:JSON.stringify(d),
                headers: { 'content-type': 'application/json' }
            });
        };
        return fact;
    });



4.Here,I validated form using $watch in above code.
5.I created a angular service LoginService that gets data from server controller (from HomeController.getLoginData() action).
6.LoginForm() method is initiated when user submits form using ngSubmit as angular attribute.

Step 6: Add View to display Login Form

1.Right click on Index action --> Add View --> add
2.Replace Index.cshtml view code with following code.

@{
    ViewBag.Title = "Login Using Angular";
}
<h2>Login Using Angular</h2>

<div ng-controller="LoginController">
    <form name="myForm" novalidate ng-submit="LoginForm()">
        <div style="color:green">{{msg}}</div>
        <table ng-show="!IsLoggedIn" class="table table-horizontal">
            <tr>
                <td>Email/UserName :</td>
                <td>
                    <input type="email" ng-model="UserModel.Email" name="UserEmail" ng-class="Submited?'ng-dirty':''" required autofocus class="form-control"/>
                    <span style="color:red" ng-show="(myForm.UserEmail.$dirty || Submited ) && myForm.UserEmail.$error.required">Please enter Email</span>
                    <span style="color:red" ng-show="myForm.UserEmail.$error.email">Email is not valid</span>
                </td>
            </tr>
            <tr>
                <td>Password :</td>
                <td>
                    <input type="password" ng-model="UserModel.Password" name="UserPassword" ng-class="Submited?'ng-dirty':''" required autofocus class="form-control"/>
                    <span style="color:red" ng-show="(myForm.UserPassword.$dirty || Submited) && myForm.UserPassword.$error.required">Password Required</span>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="submit" class="btn btn-success" />
                </td>
            </tr>
        </table>
    </form>
</div>
@section scripts{
    <script src="~/Scripts/LoginController.js"></script>
}

Add script reference at the end of Index.cshtml page.
Take a look at following things i used in above Index.cshtml view.

ng-Model: ngModel is a angular directive.it is used for two way binding data from view to controller and controller to view.In above example i used it to bind from data to angular controller.

ng-show: ngShow allows to display or hide elements based on the expression provided to ngShow attribute.

ng-submit:  ng-submit prevents the default action of form and binds angular function to onsubmit events. This is invoked when form is submitted.

$dirty: It is angular built in property. It will be true if user interacted with form other wise false.This is one of the angular validation property i used in above example.There are many validation properties in angular like $invalid,$submitted,$pristine,$valid and $error.We will learn about all these these properties in later tutorials.

Download Source code download

Conclusion: 
I hope this tutorial is understandable for every reader.Please subscribe to this www.Mitechdev.com through facebook and twitter to get daily updates.


Wednesday, 11 May 2016

Introduction to Angular JS

02:43:00 Posted by raviteja swayampu , No comments

Introduction

In this article we are going to learn about basics of angular programming.We are going to teach complete Angular JS in step by step manner.The main objective of this is to learn about angular and how it helps us to create more flexible applications, maintainable and testable web applications without comprising productivity factors.

What is Angular JS

Angular JS is a light weight java script framework that used to create web applications (Single page Applications) in a structured manner (In MVC pattern).It is best suited for creating Single page applications that used HTTP service like RestFul services.It uses MV pattern (Model View).we can also say that MVVM.

Note: Using Angular does not mean not to use Jquery we can also use Jquery in our application.Angular also internally uses lite version of jquery "JQLite".Some developers might think that Angular is only for Single page application.It is not true we can also use it in any applications if that applications demands use of Angular.But ,Angular is best suited for SPA's(single page applications).The code in Angular is structured that not like in Jquery.

Angular Advantages


The main advantage of Angular is Separation of Concern. It is one of the good thing about Good architectured applications.In Angular framework the view is a plain HTML DOM code.Controller are the java script classes and Models objects data is stored in Controller objects.These Models in Angular represents the business logic code like in Controllers in ASP.NET MVC. And this business logic is used by Views to display.Here, Controllers are responsible for data manipulation between Models and Views.
The above diagram represents the strict Model View Controller architecture.But, Angular is not really strict.We can say that Angular fits to MV(Model View).Even some developers say that it is more than fits to MVVM. It depends on how we are using it.But , we can say that Angular does not provide great separation of concern but it is flexible enough to take the architectural approach.

Contents of Angular

An Angular application mainly contains Controllers,Models and views.Here View are plain HTML that take care of displaying data to user and acting to user actions.Controller will take care of all communication between server and client(Actually this communication is done by services which are part of Controller).These Controller and views are communicates by using a shared object called $scope .

For larger applications data communication is done between server and client using Angular services.Later we will know about services in Angular.These services are reusable in the angular application.

The other components Filter and directives.Filters are used to filter the data coming from services.Angular provides large number of filters as predefined to filter data.directives are extends the HTML attributes functionality by creating custom attributes to HTML Markup.

small Definition about Angular Componets

We will learn about every component of Angular in detail in future articles.For now just take a look briefly about components.
  • Views: Views are plain HTML containing html tags along with angular specific tags.
  • Controllers: Controller is a javascript class that contains all  business logic that used by Views.
  • Models: Models are the java script entity objects that contains data.
  • Services: Services are classes that contains reusable code.(That actually communicates with server)
  • Filters: filters are used to filter the data.
  • Directives: Angular directives are the mechanism that extend the functionality of HTML markup by creating new attributes.
I think you got some basic idea of why we are learning angular js. In next tutorial we are going to learn how to setup Angular in ASP.NET MVC web application. 
click below links  for new tutorials in Angualar
Conclusion:
I think you got some basic idea of angular through this tutorial.If you recommend any modifications please comment.Please subscribe to Mitechdev.com on facebook and twitter to get daily tutorials and code samples.


Monday, 9 May 2016

How to get Data from Database using Angular js in MVC 5 application

22:03:00 Posted by raviteja swayampu , No comments
Hi every one i am very happy for your response for your previous post How to setup Angular js in ASP.NET MVC 5 application.In this tutorial i would like to explain How to get data from Database using Angular js in MVC 5 application.If your new to this angular tutorial please refer previous tutorial one it will really help you how to add angular files and configure angular js in MVC application.
In this example we are going to use $http service in Angular js. $http service in angular js is used to communicate with the remote servers for getting and setting data.In this example we are going to work on this service.

Step 1: Add a Database in application

1.In this tutorial i am using Sql Server Express(Local DB) for creating Table data.
2.Go to Solution explorer -->Right click on App_Data --> Add --> New Item -->Sql Server Data base under Data -->name it -->Add 


Step 2: Create Table in Database:

1.Open server explorer --> Expand Databasae 
2.Right click on Tables --> Add New Table -->Add columns into table and  Update database.
3.Table below columns in application.

creating new table in database

Step 3: Add Entity Data Model to application

1.Right click on Models -->Add --> New Item --> ADO.NET Entity Data Model --> name it --> Add.
2.A popup window will come (Entity Data Model Wizard) --> Select Generate from database -- > Next -- > Chose your data connection -- > select your database -- > next -- > Select tables -- > enter Model Name --> Click Finish.

ado.net entity data model in mvc5

Step 4: Create a Controller

1.Right click on Controllers -->Add --> Controller -->Select "Empty MVC Controller" -->Name it as HomeController.cs -->Add.

Step 5: Add new action into your controller for get data from Database

1.I added GetData() Json method to get fetch data from Database in HomeController
2.Add below code in HomeController.cs file
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HowtogetData_fromDatabaseusingAngular.Models;

namespace HowtogetData_fromDatabaseusingAngular.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetData()
        {
            MyDatabaseEntities db = new MyDatabaseEntities();

            Contact data = db.Contacts.OrderByDescending(x=>x.ContactID).Take(1).FirstOrDefault();

            return new JsonResult { Data = data, JsonRequestBehavior=JsonRequestBehavior.AllowGet};
        }
       
    }
}

3.Here,Index action is to render view(Index View).

Step 6: Add new script file to Add Angular js code

1.Right click Scripts --> Add --> Java script file -->name it
2.Add below code there.i named the file as myscript.js


(function () {
    //Create a Module 
    var app = angular.module('MyApp', ['ngRoute']);  // Will use ['ng-Route'] when we will implement routing
    //Create a Controller
    app.controller('HomeController', function ($scope) {  // here $scope is used for share data between view and controller
        $scope.Message = "welcome to angular js";
    });
})();

3.Here i created a angular application "MyApp" and angular controller "HomeController".The angular module initializes angular application.
4.Now add another Java script file (i named it myscript2.js).
angular.module('MyApp') //extending from previously created angular module MyApp
    //another controller we can add many controllers to angular application
.controller('Part2Controller', function ($scope, ContactService) { //inject ContactService
    $scope.Contact = null;
    ContactService.GetData().then(function (d) {
        $scope.Contact = d.data; // Success
    }, function () {
        alert('Failed'); // Failed
    });
})
.factory('ContactService', function ($http) { // here I have created a factory which is a populer way to create and configure services
    var fac = {};                               //using factory method i am configuring service.
    fac.GetData = function () {
        return $http.get('/Home/GetData');      //gets data from GetData Action in HomeController
    }
    return fac;
});

Here, a ContactService with contacts with server for data.And gets data as a response from server. ContactService is an $http angular service.

Factory : Factory metnod is to organize and share code across our app. Its moreover same like Service Layer of our asp.net application, where we write reusable code for share across our application.

#http: $http service is angular service that have ability to contact with remote servers to get and set data from server.We can make requests to multiple servers.$http is angular js core service essential for client side applications to access remote data. It communicates with remote servers using XMLHTTPRequest object.

step 7: Add View to Display Data

1.Right click Index View --> Add View --> Add.
2.replace index view code with following code.

@{
    ViewBag.Title = "Getting Data from DB using Angular";
}
<div ng-controller="Part2Controller">
        <h3 class="text-info">Contact Details</h3>
    <div class="container">
        <table class="table table-responsive table-bordered">
            <tr>
                <td>First Name :</td>
                <td>{{Contact.FirstName}}</td>
            </tr>
            <tr>
                <td>Last Name : </td>
                <td>{{Contact.LastName}}</td>
            </tr>
            <tr>
                <td>Contact No1:</td>
                <td>{{Contact.ContactNo1}}</td>
            </tr>
            <tr>
                <td>Contact No2:</td>
                <td>{{Contact.ContactNo2}}</td>
            </tr>
            <tr>
                <td>Email ID:</td>
                <td>{{Contact.EmailID}}</td>
            </tr>
            <tr>
                <td>Address</td>
                <td>{{Contact.Address}}</td>
            </tr>
        </table>
    </div>
</div>
@section scripts{
    <script src="~/Scripts/myscript2.js"></script>
}

Finally we displayed data using {{data}} Angular expressions like above.
Run application Press F5
we get,

How to get data from DB using Angualar js

Download Source code from here Downlaod
You may also like these


Conclusion:
Thank you for viewing this please subscribe to this site for daily updates.Please recommend any modifications if you want i hope you understand this tutorial. You will find more tutorials and code samples from this site.


How to setup Angular js in MVC 5 application

03:01:00 Posted by raviteja swayampu , 1 comment
angular js logo

Introduction:

Hi every one welcome again.In this tutorial i am going to explain how to setup and use Angular js in MVC 5 application.from now on wards we are going to learn about Angular js in step by step.I will cover all the topic and sample projects using angular js with MVC 5.

What is Angular JS

Angular JS is an open-source web application framework, maintained by Google and the community, that assists with creating single-page applications. Angular JS supports MVC style of application design and its primarily aimed to develop SPA(Single Page Applications). Its also support two-way binding that means your data model and control’s data will be in sync.

Form here i am going to cover angular js modules step by step from beginning to advanced level with client side using Angular js and server side using ASP.NET MVC 5.
In this tutorial we are going to learn How to setup angular js in MVC 5 application 
Please refer Introducton to Angular here explained more about angular .

Step 1: Create New MVC project

1.Go to File Menu -->New --> Project --> Select ASP.NET web application --> Enter name of application -->Choose MVC template -->Click Ok.

Step 2: Add Angular js library to project

1.You can download angular from here. or
2.You can add from Nuget Package Manager
installing angular in mvc5

3.Install Both Angular JS Core and Route files.

Step 3: Add a bundle for Angular JS library

1.Go to Solution explorer --> App_Start --> open BundleConfig.cs -->add below code there.
//Angular js bundles
      bundles.Add(new ScriptBundle("~/bundles/angular").Include(
             "~/Scripts/angular.js",
            "~/Scripts/angular-route.js"));

Step 4: Modify _Layout Pages to add Anjular

1.Replace the _Layout page with below code
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
@*
    ng-app initilizes the angular js application(Auto bootstraps)
    ng-app also tells to angular js that this <body> element-
     -is owner of created angular js application
*@
<body ng-app="myapplication">
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @*Angular js library files*@
    @Scripts.Render("~/bundles/angular")
    <script src="~/Scripts/myscript.js"></script>
    @RenderSection("scripts", required: false)
</body>
</html>

Here "ng-app" directive is used to initialize the Angular application(auto-bootstrap angular application). And here we specified that <body ng-app="myapplication"> so, <div> element is owner for angular application created.

Step 5: Add Script file to create Module and Controller

1.Right click Scripts --> Add --> Java script file --> name it as myscript.js 
2.Add below code to create angular module and Controller
    var app;
    (function () {
    //creating module in angular
    app = angular.module("myapplication", ['ngRoute']);//it uses the ngRoute if we implement routing

    //creating controller on angular
    //here $scope object is used to share data between Controller and view.

    app.controller("HomeController", function ($scope) {
        $scope.Message = "Welcome to Angular js buddy!";
        //$scope.Message = "Hi this is Two";
    })
})();
Here i added an angular $scope object to controller.

angular.module: An angular module is a collection of Controllers,Services,filters and directives etc.Module is an starting point of the Angular application. It initializes the Controllers,Services,filters at the time application is booted.Simply it is like staring point like Main() method in C# language.

angular.Controller: It contains the front end business logic like Controller in MVC application.It contains methods and variables that are used in View. Controllers also initializes $scope object.

$scope: It is a simple object.It uses angular js two way data binding to bind the controllers model data to view.$scope object is automatically created and injected using dependebcy injection when controller was intialized in angular application.

Step 6: Add Controller

1.Right click Controllers --> Add -->Controller --> Select Empty Controller --> name it HomeController.cs.
2.Then add Index Action to Controller class.
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AngularSampleApp.Controllers
{
    public class HomeController : Controller
    {
        //Index action
        public ActionResult Index()
        {
            return View();
        }
    }
}

Step 7: Add Index View to Action

1.Right click on Index action --> Add View -->Select Empty view template --> Click Add.
2.Replace it with below code.
Index.cshtml:
@{
    ViewBag.Title = "Index page";
}
<h2 class="text-info">Angular introdution</h2>

<div ng-controller="HomeController">
    {{Message}}

</div>

Here ng-controller directive specifies which controller in charge of this View.
Here, The scope of $scope object in Angular js application.

ng-controller: The ng-controller directive attaches controller to view.By using ng-controller we can attach multiple controllers to a single view.We can also attach a controller object to DOM element using ng-controller directive like above <div > element.
when a controller attached to a DOM element a new $scope object also attached to that DOM element.

Now run application

first angular application

Here, "Welcome to Angular js buddy!" text is specified in mycontroller .see code in step 5.
Download code for this here.
You may also like below
How to get data from server using Angular 

Conclusion: I hope you understand my tutorial well.We will going to learn more concepts in future tutorials.


Saturday, 7 May 2016

Learn Jquery UI part-2

21:28:00 Posted by raviteja swayampu , , No comments
jquery user interface logo

Hi every one welcome to part-2 Jquery UI learning.I hope you came across the Jquery part-1.If you do not please go for part-1 you will get more basic information click below link.
In this tutorial i am going to teach you the remaining widgets of Jquery user interface.why should waste our time lets begin tutorial.

Tabs:
Tabs are like multiple panels are placed in single area.By using this we can decrease the area to display information.

HTML Structure:
<h3 class="text-info">Jquery Tabs UI demo</h3>
    <div id="tabs">
    <ul>
        <li><a href="#tabs-1">Nunc tincidunt</a></li>
        <li><a href="#tabs-2">Proin dolor</a></li>
        <li><a href="#tabs-3">Aenean lacinia</a></li>
    </ul>
    <div id="tabs-1">
        <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p>
    </div>
    <div id="tabs-2">
        <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p>
    </div>
    <div id="tabs-3">
        <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p>
        <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p>
    </div>
    </div>

The above is the HTML structure of the Tabs.We call Tabs jquery UI using following jquery method.
$("html_selector").tabs(options);
$(function() {
    $( "#tabs" ).tabs();
  });

For advanced usage  of this UI control  visit link
Demo
jquery tabs example demo

Jqyery Menu
It is themable menu with mouse and keyboard interaction.We can also use icons along with menu options.For advanced options please click here.

Html structure:
<!--Jquery Menu demo-->
    <h3 class="text-info">Jquery Menu demo</h3>
    <ul id="menu">
    <li class="ui-state-disabled">Aberdeen</li>
    <li>Ada</li>
    <li>Adamsville</li>
    <li>Addyston</li>
    <li>
        Delphi
        <ul>
            <li class="ui-state-disabled">Ada</li>
            <li>Saarland</li>
            <li>Salzburg an der schönen Donau</li>
        </ul>
    </li>
    <li>Saarland</li>
    <li>
        Salzburg
        <ul>
            <li>
                Delphi
                <ul>
                    <li>Ada</li>
                    <li>Saarland</li>
                    <li>Salzburg</li>
                </ul>
            </li>
            <li>
                Delphi
                <ul>
                    <li>Ada</li>
                    <li>Saarland</li>
                    <li>Salzburg</li>
                </ul>
            </li>
            <li>Perch</li>
        </ul>
    </li>
    <li class="ui-state-disabled">Amesville</li>
    </ul>

Demo
jquery menu example demo
Jquery Button:
Enhances standard form elements like buttons, inputs and anchors to themeable buttons with appropriate hover and active styles.
For advanced options please click here
HTML structure:
<!--Jquery Buttons demo-->
    <h3 class="text-info">Jquery Button demo</h3>
    <button id="id_button">A sample button</button>
    <input type="submit" value="A submit button">

    <a href="#" id="link">An anchor</a>

Jquery method:
 //jquery buttons demo
        $("input[type=submit], #link,#id_button")
            .button().click(function (event) {
          event.preventDefault();
        });

Demo
jquery-button-demo
Spinner
Enhance a text input for entering numeric values, with up/down buttons and arrow key handling.
HTML structure:
<!--jquery spinner demo-->
    <h3 class="text-info">Jquery spinner demo</h3>
    <p>
    <label for="spinner">Select a value:</label>
    <input id="spinner" name="value">
    </p>

    <p>
        <button id="disable">Toggle disable/enable</button>
        <button id="destroy">Toggle widget</button>
    </p>

    <p>
        <button id="getvalue">Get value</button>
        <button id="setvalue">Set value to 5</button>
    </p>

Jquery method:
//spinner
        var spinner = $("#spinner").spinner();

        $("#disable").click(function () {
            if (spinner.spinner("option", "disabled")) {
                spinner.spinner("enable");
            } else {
                spinner.spinner("disable");
            }
        });
        $("#destroy").click(function () {
            if (spinner.spinner("instance")) {
                spinner.spinner("destroy");
            } else {
                spinner.spinner();
            }
        });
        $("#getvalue").click(function () {
            alert(spinner.spinner("value"));
        });
        $("#setvalue").click(function () {
            spinner.spinner("value", 5);
        });

        $("button").button();

To know advanced usage of this widget click here
Demo:
spinner jquery example demo
I hope you learned some basics of Jquery user interface through this tutorial.
Download source code for reference click here Download.

Conclusion:
I hope you understand this tutorial.Please if you want any modifications to this tutorial please let me know.


Learn Jquery UI Part-1

07:47:00 Posted by raviteja swayampu , , No comments
Jquery user interface tutorial

Hi Every one welcome you all again.In this article i am going to teach you about Jquery User Interface . It is a  built in java script and CSS library for creating User interfaces with help of jquery.
The official definition for jquery UI is as follows

What is Jquery UI

Jquery UI is a Curated set of User interface interactions,effects,widgets and themes built on the top of the Jquery java script library.Whether you are building highly interactive web applications and just need to add Date picker to a form,Jquery UI is perfect choice.
There are some alternatives to Jquery UI in the market but it is well worked and free to use with large number of community support.Many of web developers prefers to use Jquery UI till today.

In this tutorial i am going to teach you how to use Jquery UI Widgets in out MVC web application.The integration of Jquery UI is same for all most all web technologies like PHP,Java and python also because, it works with HTML Markup. 
following are the widget components of jquery user interface.

Jquery User interface Widget Componets:
  • Accordion
  • AutoComplete
  • Date Picker
  • Button
  • Dialog
  • Menu
  • Progress Bar
  • Select Menu
  • Slider
  • Spinner 
  • Tabs
  • Tooltip
I will explain those things one by one.Before that we need to add jquery library files to our application.

Integrate Jquery UI files in MVC application

1.Right click on Project name-->Manage Nuget packages-->serach with "Jquery  ui" and install

installing jqueryui using nuget package manager

2.Installs jquery library files in solution if any file not installed you can download from official site.
3.Add those links to application in _Layout.cshtml page which is present in Views-Shared folder.
4.Place this links in head tag.
<link href="~/Content/Bootstrap.min.css" rel="stylesheet" />
 <link href="~/Content/jquery-ui-1.11.4.css" rel="stylesheet" />
 <script src="~/Scripts/jquery-1.10.2.min.js"></script>
 <script src="~/Scripts/jquery-ui-1.11.4.js"></script>
1.Accordion:
It is a jquery UI widget displays collapsiable content panels with information in limited space
i created it with following code.i took 4 panels in <div> element.
1. i call accordion using simple function like below using simple jquery $("html_selector").accordion();
2.For advanced usage you can also use options like below.

 $(function () {

       //the comments below are options present of jquery accordion method.
        var icons = {
            header: "ui-icon-circle-arrow-e",
            activeHeader: "ui-icon-circle-arrow-s"
        };
        $("#accordion").accordion({  
         
            //icons: icons,
            //heightStyle: "content",
            //event: "click hoverintent"
        //})
        //.sortable({
        //    axis: "y",
        //    handle: "h3",
        //    stop: function (event, ui) {
        //        // IE doesn't register the blur when sorting
        //        // so trigger focusout handlers to remove .ui-state-focus
        //        ui.item.children("h3").triggerHandler("focusout");

        //        // Refresh accordion to handle new order
        //        $(this).accordion("refresh");
        //    }
        });
    });

Complete code of Accordion is,
<h2 class="text-info">Accordion demo</h2>
<style type="text/css">
    body{
        margin-top:70px;
    }
</style>
<script>
    $(function () {
        var icons = {
            header: "ui-icon-circle-arrow-e",
            activeHeader: "ui-icon-circle-arrow-s"
        };
        $("#accordion").accordion({           
            //icons: icons,
            //heightStyle: "content",
            //event: "click hoverintent"
        //})
        //.sortable({
        //    axis: "y",
        //    handle: "h3",
        //    stop: function (event, ui) {
        //        // IE doesn't register the blur when sorting
        //        // so trigger focusout handlers to remove .ui-state-focus
        //        ui.item.children("h3").triggerHandler("focusout");

        //        // Refresh accordion to handle new order
        //        $(this).accordion("refresh");
        //    }
        });
    });
</script>

    <div id="accordion">
        <h3>Section 1</h3>
        <div>
            <p>
                Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
                ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
                amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
                odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
            </p>
        </div>
        <h3>Section 2</h3>
        <div>
            <p>
                Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
                purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
                velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
                suscipit faucibus urna.
            </p>
        </div>
        <h3>Section 3</h3>
        <div>
            <p>
                Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
                Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
                ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
                lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
            </p>
            <ul>
                <li>List item one</li>
                <li>List item two</li>
                <li>List item three</li>
            </ul>
        </div>
        <h3>Section 4</h3>
        <div>
            <p>
                Cras dictum. Pellentesque habitant morbi tristique senectus et netus
                et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
                faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
                mauris vel est.
            </p>
            <p>
                Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
                Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
                inceptos himenaeos.
            </p>
        </div>
    </div>
Demo look like this
jqueryui accordion demo

2.Date picker
Date picker is a client side date picking popup
i explained every thing about how to add  date picker in MVC application here
Date picker in MVC.
3.Auto Complete
Auto complete enables users to quickly find and select from a pre populated values as they type.
 by using this user can select values easily from populated values.To learn more about this click 
1.We initiate this using below jquery method
2.We call autocomplete using simple jquery method $("html_selector").autocomplete();

$(function() {
    //values \for auto complete
    //these values comes as prepopulated
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    //auto complete init here
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });

HTML markup for this is as follows
<div class="ui-widget">
<label for="tags">Tags: </label>
  <input id="tags" />
</div>
Auto complete Demo
jquery-autocomplete-demo
4.Dialog 
Dialog displays data in an interactive way.
I already explained about this with explanation please click below to go to Modal dialog page.
Jquery Model Dialog in MVC

For next part of the tutorial please click below link(Part-2).
Learn Jquery UI part-2

Conclusion:
I hope every one understand my tutorial.please recommend if you want suggest any modifications to this article.