Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Sunday, 5 January 2014

Handling Session Timeout for Ajax Requests

ASP.Net engine is clever enough to deal with normal (non-ajax) requests when user session times out, the asp.net engine automatically redirects the user to login page specified in the web.config file.
Now, the trouble is when the request is made through ajax. The aps.net engine does its bit by redirecting the user to login page but the problem is that redirected page goes as a response to ajax response handler in the javascript. And what happens then? Something very unexpected. You will observe very weird behavior like some javascript error or a distorted UI or may be nothing.
How to deal with such situation? I will suggest here a very simple solution that may help you escape this trouble.

Add following code in the Global.asax file of your web application:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
        // This is a check for Ajax request so that other requests won't fall in this condition.
        if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
        {
            if (!Request.IsAuthenticated)
            {
                // You can set the status code to something else if you do not feel 401 as appropriate.
                Response.StatusCode = 401;
                Response.End();
            }
        }
}

Add following code in the javascript:

$(document).ajaxComplete(function (sender, e) {
        if (e.status == 401) {
            alert("Your session has timed out.");
            window.location.href = "Login.aspx";
        }
 });


Above code works if you are using Jquery else you can write the same code in onreadystatuschanged event of XMLHttpRequest.

Also keep in mind that the javascript code should be included in the master page of you application so that it is available to all the pages.



Friday, 27 December 2013

Web application client side caching

This is a very important aspect to understand that how the browser caching works and when and how to control it. I will discuss a few basic things here about the client side caching.

You can enable or disable browser caching of your web pages by specifying following tag in your application's web.config file:

 <system.web>
          <caching>  
 <outputCache  enableOutputCache="false" >  
 </outputCache>
 </caching>
 </system.web>

If you want more control over caching behavior than you should specify it in the page itself. By specifying the caching inside the webpage you can control browser caching at the page level.

Add a page directive to your webpage like this:

<%@ OutputCache Duration="1" NoStore="true" VaryByParam="*" %>

All the three attributes in this directive are required. Here we can specify the duration for which the page should be cached by setting the Duration attribute. The duration is considered in milliseconds.
With attribute VaryByParam you can specify when the page should make a fresh request. If '*' is mentioned for this attribute value that means for each parameter value in the request query string the browser will make a fresh request, if the value of any parameter changes in subsequent request.
For example if i make two subsequent request as:
http://blogger.com?id=121&tag=abc
http://blogger.com?id=122&tag=abc

In both the cases above the browser will make fresh request because the parameter value for 'id' has changed.
If you want the browser to make a fresh request on the change of particular parameter then you can specify it like, VaryByParam="tag".

By setting the value of NoStore you can specify whether you want the browser cache that page or not.

Here is a very tricky point in browser caching that you must remember or it may give you great headache at times and that is, as per the w3c standards the GET requests are always cacheable whether the caching is enabled or disabled. So whenever you are making request from javascript and do not want the page to be cached, make sure that you are making POST request.



Wednesday, 25 September 2013

ASP.Net WebMethod

One day I thought, how convenient it would have been if I could call a server method from my client script on my web page, simply, as I can call a javascript method from another javascript method.
And yes, there is the asp.net WebMethod attribute with which we can do a sever method calling as calling a method locally. WebMethod with JQuery and a little bit of JSON and we are done.
Here is the code snippet to implement the same:

Asp.Net Code

[WebMethod] 

public static string ServerMethod(string name)
{    
     return "Hi " + name;
}

WebMethod attribute requires reference to System.Web.Services.
And remember to mark the method static, otherwise it will not work.

Client Script

function GetResultFromServer()
{
   $.ajax({ type:"post",
   url: "Default.aspx/ServerMethod",
   data: JSON.stringify({name:"Boraska"}),
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function (data) {
      alert("Hurreyyy! I got " + data.d + "from server method.");
      }
  });}
This small script and WebMethod attribute do the fantastic job, no need to go in detail of page life-cycle events and many more things.
Now, here again, there are few things that needs to be taken care to make this work:
  • Url contains the method name which you want to call. Specify the url carefully. If you need you can pass query strings as well with url.
  • Data is the parameters you want to pass to the server method. The name and number of parameters must match to the server method what you are passing from here.
  • More than one parameters can be passed to the method but their types should be compatible, I mean you can pass "abc" to object type parameter but not to int type of parameter in the server method.