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 .

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

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 :::

myModule.run(['$route', '$http', function ($route, $http) {
            $http.defaults.headers.common.CustomeHeader = 'Value';
        }]);

Thanks

Standard
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();
        deferred.resolve($scope.personsFromServer);
        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-model="personId"
            ng-options="p.Id as p.Name for p in persons"
            required>
        </select>
    </div>

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 .

Cheers

Standard
Cross Domain, jQuery, jQuery AJAX

Using CORS in ASP.NET MVC Web API

Cross-site HTTP requests are HTTP requests for resources from a different domain than the domain of the resource making the request. For instance, a resource loaded from Domain A (http://domaina.example) such as an HTML web page, makes a request for a resource on Domain B (http://domainb.foo), such as an image, using the img element (http://domainb.foo/image.jpg). This occurs very commonly on the web today — pages load a number of resources in a cross-site manner, including CSS stylesheets, images and scripts, and other resources.

As an example –
If my Server is in http://www.shahjada.com and my client (which is hosted at http://www.shahjada-talukdar.com) calls that Server with an AJAX GET , it will give an error for Cross Domain Issue .

If the Client and Server is in the same server but in different port , It will also give Cross Domain error . Only if Client and Server are in same Address , it will work nicely.

Suppose , My ASP.net MVC WebAPI is hosted at http://www.shahjada-talukdar.com and my client is in http://www.shahjada.com , It will throw the error .
We can fix this issue by Using Cross Origin Resource Sharing (CORS) in ASP.NET Web API Server .

For that , We can create a CORS handler and add that handler to GlobalCOnfiguration’s MessageHandler .
My Cors handler is something like this :

public class CorsHandler : DelegatingHandler
    {
        const string Origin = "Origin";
        const string AccessControlRequestMethod = "Access-Control-Request-Method";
        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool isCorsRequest = request.Headers.Contains(Origin);
            bool isPreflightRequest = request.Method == HttpMethod.Options;
            if (isCorsRequest)
            {
                if (isPreflightRequest)
                {
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                    string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                    if (accessControlRequestMethod != null)
                    {
                        response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                    }

                    string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
                    if (!string.IsNullOrEmpty(requestedHeaders))
                    {
                        response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                    }

                    TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                    tcs.SetResult(response);
                    return tcs.Task;
                }
                else
                {
                    return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
                    {
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                        return resp;
                    });
                }
            }
            else
            {
                return base.SendAsync(request, cancellationToken);
            }
        }
    }

Now Add that to Global.asax.cs like below :

GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());

Now our Server is ready to handle any Cross Domain Client’s Call .

Cheers 🙂

Standard
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" />
        </asp:DropDownList>

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 %>");
         

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

My Server side code of the WebService is :::

[WebMethod]
         [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

Standard
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 () {

            $.ajax({

                type: "POST",
                url: "jQueryAjaxData.aspx",
                data: "a=2&b=3",
                success: function (data) {
                    $("#divResult").text(data);
                }

            });

        });
    
    </script>

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 🙂

Standard