2LeggedSpider

Handling Exceptions using jQuery and ASP.NET MVC

Posted in AJAX, ASPNETMVC, jquery by Sumit Thomas on December 22, 2009

[tweetmeme style=”compact”] Using AJAX has become one of the de facto practices in many web based RIAs. The use of jQuery is on the rise in many web applications, especially the ones built using ASP.NET MVC. Making AJAX calls using jQuery is quick and easy. A typical web request can have an expected response or an exception. It is therefore important to catch exceptions when we make any AJAX calls so that we can show some message which makes sense to the user.

Lets begin with our Controller. Create the following method to throw JSON version of the exception.

        private JsonResult ThrowJSONError(Exception e)
        {
            Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
            //Log your exception
            return Json(new { Message = e.Message});
        }

Specifying the StatusCode as HttpStatusCode.BadRequest or HttpStatusCode.InternalServerError or simply 500 will let the javascript know that there is something wrong in the response.

Lets create an ActionMethod to throw an exception which we will catch using jQuery.

        public ActionResult DivideByZero()
        {
            try
            {
                throw new DivideByZeroException();
            }
            catch (DivideByZeroException e)
            {
                return ThrowJSONError(e);
            }

        }

The above method will throw a DivideByZeroException which will be converted to a JSON string in the catch block and returned to the caller. Lets write the jQuery code to call the ActionMethod.

        $(document).ready(function() {
            $.ajax({
                type: "GET",
                url: "AJAX/DivideByZero",
                dataType: "json",
                success: function(data) {
                    if (data) {
                        alert("Success!!!");
                    }
                }, error: function(xhr, status, error) {
                    DisplayError(xhr);
                }
            });
        });

        function DisplayError(xhr) {
            var msg = JSON.parse(xhr.responseText);
            alert(msg.Message);
        }

Here we are making a call to the DivideByZero ActionMethod. Obviously the exception will be thrown,which will be caught in the error block. The responseText is a string of serialized data, which will not be useful unless we parse it to JSON. We can use the native JSON parser available in the latest browser. But, this as I found out is not helpful in IE 7 or lower. Fortunately, there is a useful library at JSON.org that can parse the responseText to JSON.

Let me know if there are better ways of handling exceptions in jQuery.

Hope you found it useful!

Advertisements
Tagged with: , ,

Generating a Shorter URL using bit.ly API and jQuery

Posted in AJAX, jquery by Sumit Thomas on December 18, 2009

[tweetmeme style=”compact”]Here is a simple jQuery script to generate shorter URL using the bit.ly API.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>URL Shortening</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnShort").click(function() {
                var longUrl = $("#longUrl").val();
                var shortUrl = $("#shortUrl");
                shortUrl.html("Loading...");
                var params = {
                    version: "2.0.1",
                    longUrl: longUrl,
                    login: "bitlyapidemo",
                    apiKey: "R_0da49e0a9118ff35f52f629d2d71bf07"
                };
 
                $.getJSON("http://api.bit.ly/shorten",
                { version: params.version, longUrl: params.longUrl, login: params.login, apiKey: params.apiKey },
                function(data) {
                    shortUrl.html(data.results[longUrl].shortUrl);
                });
            });
        });
 
    </script>

</head>
<body>
    <input type="text" id="longUrl" /><input type="button" id="btnShort" value="Shorten!" />
    <br />
    <div id="shortUrl" />
</body>
</html>

URL Shortening

You can go through the bit.ly API documentation and try out the remaining methods as well.

Tagged with: , ,

Check availability of Username using ASP.NET MVC and jQuery

Posted in AJAX, ASPNETMVC, jquery by Sumit Thomas on August 17, 2009

[tweetmeme style=”compact”]Here is a simple way to check if an Username is available using ASP.NET MVC and jQuery

Step 1: First lets create the XHTML markup for our View page(Index) as follows…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Check if an Username already exists</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
//Your jQuery code will come here
</script>
</head>
 
<body>
    Enter a Username: <br />
    <input type="text" id="txtUsername" />
    <input type="button" id="btnCheck" value="Check!" />
    <div id="divStatus" />
</body>
</html>

So your view will look like this…

jQuery Username check

Step 2: Create a Controller class ‘UniqueNameController’ or WhateverController as follows…

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyMVCTrials.Controllers
{
    [HandleError]
    public class UniqueNameController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult CheckName(FormCollection form)
        {
            System.Threading.Thread.Sleep(3000);
            string name = form["username"];

            if (name.Equals("Sumit")) 
                return Json(false);
            return Json(true);
        }
    }
}

The Action Method CheckName contains the logic to check if the Username provided already exists or not. The code provided here is only for demo. Thread.Sleep(3000) will simulate a delay as if to show that the application is working really hard to find out if the username exists or not. REMOVE that line when you are writing the actual code to check the username against a database or Web service.

NOTE: The return value need not be a JsonResult. You can change it to ActionResult and return some string value to indicate the success/failure of the call.

Step 3: Lets replace the comment Your jQuery code will come here from our view with the following jQuery code…

        $(document).ready(function() {
            $("#btnCheck").click(function() {
                var name = $("#txtUsername").val(); //Value entered in the text box
                var status = $("#divStatus"); //DIV object to display the status message
                status.html("Checking....") //While our Thread works, we will show some message to indicate the progress

                //jQuery AJAX Post request
                $.post("/Home/CheckName", { username: name },
                    function(data) {
                        if (data == "true") {
                            status.html(name + " is available!");
                        } else {
                            status.html(name + " is not available!");
                        }
                    });
            });
        });

The code is very simple. The button click event makes an AJAX call to our ActionMethod CheckName and expects a response. The Thread.Sleep(3000) will delay the response for 3 seconds. The ActionMethod checks the value of the username and returns a JSON string for our AJAX call to handle.

We can fancy it up a bit by providing some color to our status messages using the jQuery addClass method. Putting it all together, our View will looks as follows…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Check If Name Already Exists</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <style type="text/css">
        .green
        {
            color: Green;
        }
        .red
        {
            color: Red;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnCheck").click(function() {
                var name = $("#txtUsername").val();
                var status = $("#divStatus");
                status.html("Checking....").removeClass();
                $.post("/Home/CheckName", { username: name },
                    function(data) {
                        if (data == "true") {
                            status.html(name + " is available!").addClass("green");
                        } else {
                            status.html(name + " is not available!").addClass("red");
                        }
                    });
            });
        });
    </script>
</head>
<body>
    Enter a Username:
    <br />
    <input type="text" id="txtUsername" />
    <input type="button" id="btnCheck" value="Check!" />
    <div id="divStatus" />
</body>
</html>

Checking the username
Progress

Username already exists
Not Available

Username is available
Available

There are different ways in which you can make AJAX requests using jQuery. For the detailed documentation check http://docs.jquery.com/Ajax. Hope it was useful!

Tagged with: , , ,

Script#

Posted in AJAX, C#, technology by Sumit Thomas on August 18, 2006

I recently came across Nikhil Kothari’s blog and his pet project Script#. Nikhil is an architect at the Web platform and tools team in Microsoft. Check out his blog http://www.nikhilk.net/

Here is his video on Script#

Tagged with: ,

Hands on AJAX

Posted in AJAX by Sumit Thomas on December 15, 2005

AJAX is one of the Buzz words in Web development nowadays, thanks to some cool implementation by Google in gmail.com.

More information on AJAX could be found here

I tried a sample implementation of AJAX. I started off by creating a Web form in ASP.NET.

The source code of the Web page is as follows:

public void Page_Load(
object sender, EventArgs e )
{
SqlConnection con = new
SqlConnection("server=(local);user id=sa;pwd=;database=northwind");
SqlCommand cmd = new SqlCommand("select * from employees order by LastName",
con);
con.Open();
SqlDataReader dr =
cmd.ExecuteReader(CommandBehavior.CloseConnection);
while( dr.Read() )
{
Response.Write( dr["FirstName"].ToString() + ", " +
dr["LastName"].ToString() + "
");
}
dr.Close();
}

Save this page as db.aspx

The code is very simple. I am connecting to the Northwind database and displaying the Employee names from the Employees table.

Now the server side page need not be a ASP.NET page, it could be PHP, ASP, JSP or any other server side script.

The source code for the client side page is as follows:

var X=null;

//Function to get the XMLHTTP Object. Gets it in a IE/Mozilla friendly way.
function
getXMLHTTP(){
var X;
//For IE
try{
X=new
ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
X=new
ActiveXObject("Microsoft.XMLHTTP");
} catch(oc){
X=null;
}
}
//For Non-IE browsers
if(!X &amp;&amp; typeof XMLHttpRequest !=
"undefined") {
X=new XMLHttpRequest();
}
return X;
}

//This function is called in the document onLoad event to fill the DIV tag
//with the data from the server side web page.
function FillData(d)
{
//Return if the XMLHTTP object is already initialised or in use
if(X &amp;&amp; X.readyState!=0){
X.abort()
}

X=getXMLHTTP();

d = document.getElementById(d);
eval(d).innerText = "Loading....";

if(X){

//Use the object's open method and pass the required arguments.
//First argument is the method, GET or POST
//Second argument is the web page's URL
//Third argument is to mention if the process should be asynchronous or not
X.open("GET","db.aspx",true);

// This function is called only if we get a complete response from the web page.
X.onreadystatechange=function() {

if(X.readyState==4&amp;&amp;X.responseText) {
// Once we get the complete response, pass the response text to the Div tag.
eval(d).innerHTML
= X.responseText;
}
};
}
X.send(null);
}

function
Fill()
{
FillData("disp");
}


<div id="disp">
</div>

Save this page as a HTML file.

Place both the files in web server and if you run the HTML file you should see the data from Employee table populating the DIV tag. This works in the latest version of IE, FireFox and Opera.

Technorati: , , ,
Tagged with: