AngularJS, ASP.Net MVC, JavaScript, jQuery, jQuery AJAX, MVC WebAPI

Add Request Header for REST API Calling with AngularJS & jQuery

In the Web World , We always call REST APIs from our Web Applications .

When We call REST APIs through jQuery or AngularJS , they added few default Request Headers .

But many a time , we need to pass Custom Request Headers for different purposes.

A Common scenario is for Authentication we need to pass Customer Request header .

But how we can add this ?

Lets see the below samples :::

for jQuery , we can easily add Request Headers when we do AJAX Calling .

            type: "POST",
            url: '/api/test',
            data: myObj,
            headers: { 'Custom-Header': 'Value'},
            success: function (resp) {
            error: function (x, y, z) {

In AngularJS , If we use $http for REST API calling , we can add Request Header like below , after we create AngularJS Module , we can do :::['$route', '$http', function ($route, $http) {
            $http.defaults.headers.common.CustomeHeader = 'Value';


AngularJS, HTML5, JavaScript

Using HTML5 LocalStorage with AngularJS

Today , I will talk about LocalStorage Support of HTML5.

We can store named key/value pairs locally, within the client web browser. Like cookies, this data persists even after you navigate away from the web site, close your browser tab, exit your browser, or what have you. Unlike cookies, this data is never transmitted to the remote web server (unless you go out of your way to send it manually). Unlike all previous attempts at providing persistent local storage, it is implemented natively in web browsers, so it is available even when third-party browser plugins are not.

8.0+ 3.5+ 4.0+ 4.0+ 10.5+ 2.0+ 2.0+

Based on different browsers , we can get 2 MB to 5MB (even more) space in LocalStorage . To get more idea on space check out this link …

BY the below code , we can check our browser supports LocalStorage or Not !

function supports_html5_storage() {
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
        return false;

Also we can use Modernizr to check this .

if (Modernizr.localstorage) {
    // window.localStorage is available!
} else {
    // no native support for HTML5 storage :(

Lets develop a simple LocalStorage Cache framework with AngularJS .

For this , am gonna create an AngularJS Factory Service to communicate with the HTML5 LocalStorage .

'use strict';

valApp.factory('storageService', function ($rootScope) {

    return {
        get: function (key) {
           return localStorage.getItem(key);

        save: function (key, data) {
           localStorage.setItem(key, JSON.stringify(data));

        remove: function (key) {
        clearAll : function () {

localStorage keyword in the upper is the core API which is responsible for providing LocalStorage facility .

I have not used this storageService directly in the client .I am gonna use another Mid Layer Factory which will communicate with storageService and client code will call this Mid Layer Factory named cacheService . This is like below :::

'use strict';

valApp.factory('cacheService', function ($http, storageService) {
    return {
        getData: function (key) {
            return storageService.get(key);

        setData: function (key,data) {
  , data);
        removeData: function (key) {

You can see , I have injected storageService to cacheService .

Now from my AJs Controller , I will call cacheService’s Function to serve my purpose .

Now below is the example , how you can use this Cache Framework …

In My Controller , I’ve simply injected cacheService and can use all the features of it .

var city = [
                  { Id: 1, Name: 'Dhaka' },
                  { Id: 2, Name: 'Ctg' }
    cacheService.setData('city', city);

I have used the Mid Layer , if we need any new logic later, we can easily add those to the Mid Layer .

Its easy and awesome , right ?

Cheers 🙂

AngularJS, JavaScript

AngularJS : Using Promise-Part1

In Modern Web (Web 2.0) , We use so many Asynchronous call in our Web Applications . But sometimes , we need that , A Call is depended on another call .That means – After First Method’s Success CallBack another Method should be called . So if both the call occurs asynchronously , It does not fit my requirement .

So We can use AngularJS Promise to do this kind of things .

Lets see an example .

app.controller('PersonCtrl', ['$scope', '$rootScope', '$http', '$q', 'setting', function($scope, $rootScope, $http, $q, setting) {
    $scope.personsFromServer = [
        { Id: 1, Name: 'Shahjada' },
        { Id: 2, Name: 'Talukdar' },
        { Id: 3, Name: 'Masoom' }

    var getPersonPromise = function() {
        var deferred = $q.defer();
        return deferred.promise;

    getPersonPromise().then(function(persons) {
        $scope.persons = persons;
        $scope.personId = persons[0].Id;
    }, function (reason) {
        alert('Failed: ' + reason);

I am mocking PersonsFromServer Data in my example (Suppose this is gonna come from Server By an asynchronous call) .Now I am gonna populate a DropDown after successfully returning the data , and am selecting the first Person as selected Item in DropDown .

<div ng-controller="PersonCtrl">
        <select id="Person"
            ng-options="p.Id as p.Name for p in persons"

The Deferred API

A new instance of deferred is constructed by calling $q.defer().

The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion of the task.

The Promise API

A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise.

The purpose of the promise object is to allow for interested parties to get access to the result of the deferred task when it completes.

Hope you got the idea .

Thanks .
In Part2 , I will show Calling API from Server with Resource and of course with Promise .


ASP.Net, C#, JavaScript

Show JavaScript Confirmation message while deleting ASP.Net Grid Row

Many a time , we need a confirmation Message on deleting ASP.Net Gird Row . Coz if any User mistakenly clicks the delete button , the data will be gone . So its always the Best to use Confirmation on Deleting .

We will see a demo now how to Show JavaScript/Client Side Confirmation Msg while deleting an ASP.Net Grid Row .

A long time ago ,I had to use more brain processing power to do this requirement 🙂 So I thought to share with all .

Lets see the below image for what I am gonna do :

Show JavaScript Confirmation message while deleting  ASP.Net Grid Row

Show JavaScript Confirmation message while deleting ASP.Net Grid Row

Add this markup inside your ASP.Net Grid .

<asp:TemplateField HeaderText="" ShowHeader="False" HeaderStyle-HorizontalAlign="Left">
                                      <asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False" CommandName="Delete"
                                    Text="Delete" OnClientClick="ConfirmDelete(" ></asp:LinkButton>
                            <HeaderStyle HorizontalAlign="Left" />

And the JavaScript method implementation of the ConfirmDelete( is like below –

function ConfirmDelete(RowId)
         var rowNoStr = RowId.split('_');
         rowNo = parseInt(rowNoStr[3]) + 1;              
         var confirm_value = document.createElement("INPUT");
         confirm_value.type = "hidden"; = "confirm_value";

         var grid = document.getElementById('<%=gvTicketDetails.ClientID%>');

         var delText = "Are you sure to delete - ";
         var ticketNo ="Tk " + grid.rows[rowNo].cells[0].innerText + " : ";
         var ticketTitle = grid.rows[rowNo].cells[1].innerText + " ?";
         var delMsg = delText.concat(ticketNo, ticketTitle);

         var answer = confirm(delMsg);
         if (answer)
             confirm_value.value = "Yes";
             confirm_value.value = "No";

And now using the below code , you can easily get the confirmation value at server side .

protected void gvTicketDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
            string confirmValue = Request.Form["confirm_value"];
            if (confirmValue.ToUpper() == "YES")

You are done 🙂 Cheers

AngularJS, ASP.Net, HTML5, HTTP & HTTPS, JavaScript, jQuery, jQuery AJAX

How HTTPS Works : Part1

I wanted to write a basic article on How HTTPS works , then I got this below article , so am gonna share his Article here . Hope , all will enjoy this one .

And I will write more on HTTPS in Part2,3… etc …

Cheers 🙂

ASP.Net, C#, JavaScript, jQuery, jQuery AJAX

How to Call ASMX WebService using HTTP GET with jQuery AJAX

By Default , WebMethod of ASMX is not allowed to be called using HTTP GET . So we will see a short demo here . Our HTML Markup of the aspx page is :

<asp:DropDownList ID="DropDownList2" runat="server" Width="150">
           <asp:ListItem Text="Select" Value="-1" />

We will fill this DropDown By calling ASMX Service’s WebMethod using HTTP GET with jQuery Ajax . My Client Code is like below :::

var DropDownList2 = $("#<%= DropDownList2.ClientID %>");

                type: "GET",
                url:"<%=ResolveUrl("~/MyWebService.asmx") %>/GetAllProjectName",
                contentType:"application/json; charset=utf-8",
                success: function(response){
                        var projects = response.d;
                            DropDownList2.append('<option value="'+ project.ProjectId +'" >' + project.ProjectName + '</option>');                        

My Server side code of the WebService is :::

         [ScriptMethod(UseHttpGet = true)]
         public List<ProjectOfEmployee> GetAllProjectName()
             return GetProjectName();   

Remember to add the below part of course

[ScriptMethod(UseHttpGet = true)]

Otherwise , It will give 500 Internal Server Error .

So now you are done 🙂 Cheers

ASP.Net, C#, JavaScript, jQuery, jQuery AJAX

jQuery Ajax in Action with ASP.Net aspx Page

Most of the time , We call our custom WebServices/REST Services/Third Party REST APIs from any jQuery AJAX based HTTP Verb . But we can also call direct ASP.Net Form Page( which is aspx page ) using jQuery AJAX .

Here is how we can call ASPX page from another ASPX page’s AJAX Method.

For this example , I have used two ASPX page –

1.AjaxCheckPage.aspx ::: From this page I am gonna call another ASPX Page
2.jQueryAjaxData.aspx ::: This Page will be called by jQuery AJAX

HTML Markup of my AjaxCheckPage.aspx is like below :

<input type="button" id="ajaxButton" value="Load Data using jQuery Ajax" />   

     <div id="divResult"></div>

Ajax calling code of this Page is —

    <script language="javascript" type="text/javascript">

        $("#ajaxButton").click(function () {


                type: "POST",
                url: "jQueryAjaxData.aspx",
                data: "a=2&b=3",
                success: function (data) {



So Now , am doing like – If any Data comes from jQueryAjaxData.aspx , that means after successful , am binding the data to the DIV :

Now lets go another Page jQueryAjaxData.aspx from which the Data is gonna come .

protected void Page_Load(object sender, EventArgs e)
            if (Request.Form["a"] != null && Request.Form["b"] != null)
                int a = int.Parse(Request.Form["a"]);
                int b = int.Parse(Request.Form["b"]);
                int sum = a + b;
                Response.Write("The Sum is : " + sum);

jQuery Ajax in Action with ASP.Net aspx Page

jQuery Ajax in Action with ASP.Net aspx Page

So you can see , when I click the button then It request a POST to jQueryAjaxData.aspx page and am also passing Form Data as you can see it inside the picture above .

So , this is how , we can call ASPX page from jQuery AJAX POST .

Cheers 🙂