SimpleDropDownEffects – A jQuery plugin for transforming select drop-down lists with some amazing expanding effects.

I recently bumped into this page on GITHUB and found this simple and easy to use jquery plugin which transform a simple select drop down list to a drop down list with some amazing jquery effects.

Untitled

Above shown screenshots are taken from this demo page. I personally found the plugin very easy to use, let me quickly show you how to set this plugin up, heres a link to the fiddle i created : http://jsfiddle.net/yrshaikh/B3y8e/.

Step 1: Download the zip package from its github page and inlcude the js and css file in your project, there is one js file named jquery.dropdown.js which you need to include you may also want to include the modernizr.js incase you haven’t already.

Step 2: Your HTML

<select id="cd-dropdown" class="cd-select">
    <option value="-1" selected>Actions</option>
    <option value="1">View</option>
    <option value="2">Edit</option>
    <option value="3">Delete</option>
</select>

Step 3: Jquery

$('#cd-dropdown').dropdown();

And voila its done ! dropdown demo

I have also created a fiddle for this here : http://jsfiddle.net/yrshaikh/B3y8e/ hope this helps :)

Cheers !

Using Twitter typeahead.js with ASP.NET MVC Web API

There are many auto-complete jQuery libraries I have used before, like jQuery UI’s Autocomplete, loopJ’s jQuery Tokeninput and Select2. But one of my colleague at work, recently introduced me to this jQuery plugin called twitter’s typeahead.js, it seemed to be good, so we decided to use it in one of our ongoing project.

So, What is typeahead.js ? typeahead.js is a fast and fully-featured autocomplete library. You can check out some of the basic examples from here or you can hit straight to the docs from here.

Lets get started with a few basic examples.

1. Things you’ll need to download: You can download the latest version of typeahead.js from here. Below are the js and css you’ll need to include :

<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.js" />
<link href="http://twitter.github.io/typeahead.js/css/examples.css" rel="stylesheet" />

2. Local data example: (fiddle)

<input type="textbox" placeholder="Search Song" id="search-box" />

<script type="text/javascript">
$('input#search-box').typeahead({
  name: 'name',
  local: ['yasser', 'shyam', 'sujesh', 'siddhesh', 'vaibhav']
});
</script>

typeAhead-local

3. MVC Web Api example :

public class SongController : ApiController
{

    public JsonResult GetSongs(string searchTerm)
    {
        List<Songs> songList = new List<Songs>();
        songList.Add(new Songs{ Name = "Addat", Artist = "Aatif Aslam", Year = "2007"});
        songList.Add(new Songs{ Name = "Woh Lamhey", Artist = "Jal - The band", Year = "2008"});
        songList.Add(new Songs{ Name = "Kryptonite", Artist = "3 Doors Down", Year = "2009"});
        songList.Add(new Songs{ Name = "Manja", Artist = "Amit Trivedi", Year = "2013"});
        songList.Add(new Songs{ Name = "Tum hi ho", Artist = "Arjit Singh", Year = "2013"});

        songList = songList.Where(m => m.Name.Contains(searchTerm)).ToList();

        return songList;
    }
}

public class Songs
{
    public string Name { get; set; }
    public string Year { get; set; }
    public string Artist { get; set; }
}

$("#search-box2").typeahead({
    name: 'songs',
    valueKey: 'Name',
    remote: {
        url: '/Song/GetSongs?searchTterm=%QUERY'
    }
}); 

Hope this helps :)

Auto complete in text area with jQuery aSuggest

jQuery.asuggest is a small light weight plugin that can be used to implement auto-complete with textareas. This plugin requires the following two js

jQuery.asuggest can be downloaded from here or from its GitHub page. Lets quickly dive into an example :

Html : (jsFiddle link)

<textarea rows="10" cols="55" id="comment"></textarea>

Jquery : (jsFiddle link)

$(document).ready(function(){

    var suggests = ["hello", "android", "world", "is", "all", "over", "under"];
    $("#comment").asuggest(suggests);    

});

Output : http://jsfiddle.net/yrshaikh/JbYdx/embedded/result/
jquery asuggest output

More examples

jQuery UI autocomplete with ASP.NET Web API

jQuery UI autocomplete enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

Step 1 : Getting Web Api Ready

Lets first create a web api method that will return a list of item (Artists) using the search term query sent from the autocomplete textbox. In this post I am not using database, instead I’ll be using List to keep this example as simple as possible.

Below is how I have defined my Artist class

public class Artist
{
    public int Id { get; set; }
    public int Name { get; set; }
}    

Next I have created a Web Api GET method that will use the search term entered in the autocomplete textbox and with a little help of LINQ will return a list of matching results.

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

namespace Autocomplete.Controllers
{
    public class ArtistApiController : ApiController
    {

        public List<Artist> ArtistList = new List<Artist>
        {
            new Artist{Id = 1, Name = "Sonu Nigam"},
            new Artist{Id = 2, Name = "Sunidhi Chauhan"},
            new Artist{Id = 3, Name = "Shreya Goshal"},
            new Artist{Id = 4, Name = "Mohit Chauhan"},
            new Artist{Id = 5, Name = "Nihkil Dsouza"},
            new Artist{Id = 6, Name = "Kailash Kher"},
            new Artist{Id = 7, Name = "Atif Aslam"},
            new Artist{Id = 8, Name = "Ali Zafar"},
            new Artist{Id = 9, Name = "Shafaqat Ali"},
            new Artist{Id = 10, Name = "Shankar Madahevan"}
        }; 


        // GET api/values
        public IEnumerable<Artist> Get(string query)
        {
            return ArtistList.Where(m => m.Name.Contains(query)).ToList();
        }
    }
}   

Our server side code is ready ! Time to test it out.

autocomplete test

Step 2 : Client side code

Include jquery-ui.js and jquery.ui.css in your html

<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js" ></script>
<script type="text/javascript" src="~/Scripts/jquery-ui-1.8.20.min.js" ></script>
<link href="~/Content/themes/base/jquery.ui.all.css" rel="stylesheet" />

<div id="body">
    <label for="autocomplete-textbox">Search : </label>
    <input type="text" id="autocomplete-textbox" />
</div>

<script type="text/javascript">
$(document).ready(function (){
$('#autocomplete-textbox').autocomplete({
    source: function (request, response) {
        // prepare url : for example '/api/artistapi?query=sonu
        var autocompleteUrl = '/api/artistapi' + '?query=' + request.term;
        $.ajax({
            url: autocompleteUrl,
            type: 'GET',
            cache: false,
            dataType: 'json',
            success: function (json) {
                // call autocomplete callback method with results  
                response($.map(json, function (data, id) {
                    return {
                        label: data.Name,
                        value: data.Id
                    };
                }));
            },
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                console.log('some error occured', textStatus, errorThrown);
            }
        });
    },
    minLength: 2,
    select: function (event, ui) {
        alert('you have selected ' + ui.item.label + ' ID: ' + ui.item.value);
        $('#autocomplete-textbox').val(ui.item.label);
        return false;
    }
});
});
</script>

One thing to note here is that inside the success method I have used the following code :

response($.map(json, function (data, id) {
    return {
        label: data.Name,
        value: data.Id
    };
}));

data.Id and data.Name is used because in the ajax response (as shown below) data is returned in this format.

autocomplete ajax response

Step 3 : Test & Output :

autocomplete output

Hope this helps :)

How to use if else statements in underscore.js template ?

There is always a need to have a condition check when populating your underscore.js tempalte. For instance in my case I had a model and few fields in the model had null values so when they were rendered with these values, I got an output like the one shown below :

This clearly isn’t right, instead what should have happened here was, whenever the data in model was ‘null’ the text box should have been left empty. So here is how this is done in underscore.js template :

<div class="editor-label">
  <label>First Name : </label>
</div>

<div class="editor-field">
    <% if(FirstName == null) { %>
        <input type="text" id="txtFirstName" value="" />
    <% } else { %>
        <input type="text" id="txtFirstName" value="<%=FirstName%>" />
    <% } %>
</div>

Further Reading

Ajax call : User Aborted error vs Other Ajax Error

In an application I am working on recently, I was required to make an AJAX call to load a jqgrid with data. Incase of failure while getting the data, I had used the AJAX function’s error() method to show a error message to the user that “There has been some error while loading your data”. But soon I noticed I started getting the same error message even when I navigated away from the page before the AJAX call has finished. Some search on this led me to this article by Brian Morearty who also had the same problem. Here is what I use now…

The trick is to check the response headers in the XMLHttpRequest object. If there are no response headers (null or empty string, depending on the browser), the server did not respond yet. That means the user aborted.

$.ajax({ 
  url: "url-to-go-here",
  success: function() { }, 
  error: function(xhr, textStatus, errorThrown) {
    if(!isUserAborted(xhr)) {
      console.log("Ajax Error") 
    }
  }
});

function isUserAborted(xhr) {
  return !xhr.getAllResponseHeaders();
}

Hope this helps :)

Related Post :

How to call web api method using jquery ajax in ASP.NET MVC 4

This tutorial will cover the following types of calling a web api method using jquery ajax.

  • Call a GET method without parameters
  • Call a GET method with a single parameter
  • Call a GET method with multiple paramerer
  • Call a POST method with multiple parameter

Before we start, Let me quickly created an api controller. Below is an api controller named “EmployeeController”, which will be used throughout all the examples.

public class EmployeeController : ApiController
{
    List<Employee> _employeeList = new List<Employee>
      {
          new Employee {FirstName = "Yasser", LastName = "Shaikh", Age = 24, DepartmentName = "S/W Engg"},
          new Employee {FirstName = "Roshan", LastName = "Punwani", Age = 25, DepartmentName = "SQL"},
          new Employee {FirstName = "Siddhesh", LastName = "Vasani", Age = 45, DepartmentName = "Sharepoint"},
          new Employee {FirstName = "Shival", LastName = "Sharma", Age = 36, DepartmentName = "Java Games"}
      };

    // all methods to come here.
}

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string DepartmentName { get; set; }
}

Ok, lets get started…

Type 1 : Call a GET method without parameters

Let us first create a GET method that does NOT accept any input parameters, this method will return a list of all the employees.

public List<Employee> GetAllEmployees()
{
   return _employeeList;
}

URL : http://localhost:1235/api/employee/

Using this url in the browser will give you the following output.

Web Api - GETWeb Api - GET

Jquery Ajax Call :

<script type="text/javascript">
$(document).ready(function () {
    var url = '/api/Employee';
    $.ajax({
        url: url,
        type: 'GET',
        success: function (result) {
            // use the result value here.
        }
    });
});
</script>

Console Output

Web Api - GET - Console log


Type 2 : Call a GET method with a single parameter

This method takes in the first name of the employee and returns a list of matching employees

public List<Employee> GetEmployeeByFirstName(string fname)
{
    return _employeeList.Where(m => m.FirstName == fname).ToList();
}

URL : http://localhost:1235/api/employee?fname=Yasser

Using this url in the browser will give you the following output.

Web Api - GET Single Param

Jquery Ajax Call :

<script type="text/javascript">
$(document).ready(function () {
    var fname = "Yasser"; // can be a value from a txtbox
    var url = '/api/Employee?fname=' + fname;
    $.ajax({
        url: url,
        type: 'GET',
        success: function (result) {
            // use the result value here.
        }
    });
});
</script>

Console Output

Web Api - GET Single Param - Console


Type 3 : Call a GET method with a multiple parameter

This method takes in the first name, last name and the age of the employee and returns a list of matching employees

public List<Employee> GetEmployeeByMultipleParams(string fname, string lname, int age)
{
   return _employeeList.Where(m => m.FirstName == fname && m.LastName == lname && m.Age == age).ToList();
}

URL : http://localhost:1235/api/employee?fname=Yasser&lname=Shaikh&age=24

Using this url in the browser will give you the following output.

Web Api - GET Multiple Param

Jquery Ajax Call :

<script type="text/javascript">
$(document).ready(function () {
    var fname = "Yasser"; // can be a value from a txtbox
    var lname = "Shaikh"; // can be a value from a txtbox
    var age = 24; // can be a value from a txtbox
    var url = '/api/Employee?fname=' + fname + "&lname=" + lname + "&age=" + age;
    $.ajax({
        url: url,
        type: 'GET',
        success: function (result) {
            // use the result value here.
        }
    });
});
</script>

Console Output

Web Api - GET Multiple Param - Console


Type 4 : Call a POST method with a multiple parameter

public bool PostEmployee(Employee employee)
{
    return _service.UpdateEmployee(employee);
}

Jquery Ajax Call :

<script type="text/javascript">
$(document).ready(function () {

    var url = '/api/Employee/PostEmployee';
    $.ajax({
        url: url,
        data: getData(),
        type: 'POST',
        contentType: "application/json",
        success: function (result) {
            console.log(result);
        }
    });

    function getData() {
        var employee = new Object();
        employee.FirstName = "Yasser R";
        employee.LastName = "Shaikh";
        employee.Age = "25";
        employee.DepartmentName = "S/W Engg";

        return JSON.stringify(employee);
    }
});

Hope this helps :)

Further Reading :

Net Tuts + : Building an ASP.NET MVC4 Application with EF and WebAPI

Web API : The Official Microsoft ASP.NET Site

Date.js conflicting with JqPlot, How to solve ?

Date.js has always been my first choice JavaScript Date Library for parsing, formatting and processing dates. Similary, I always use JqPlot to generate graphs (line, bar, bubbles, etc.)

But…

When these two plugins used together, it resulted into this problem. With virtually no alternative / quick fix. I had to settle with Moment.js.

Today with over a month of use with Moment.js, I am very happy with Moment.js. I had recently blogged about it here. Hope you found this helpful :)

Introduction to using Moment.js and some basic Moment.js commands.

Moment.js is cool alternative to Date.js. Not that I have any grudges for Date.js, Date.js is an equally cool date time plugin, only because I ran into some issue as stated here have I decided to ditch Date.js for Moment.js. Here is a list of all good date manipulation javascript plugins.

You can check out the documentation for moment.js here, or dive straight into their source code here(Minified Source &
Full Source).

For ASP.NET MVC developers there is a nuget extension available here. To use Moment.js with ASP.NET MVC.

Below are few examples I created using Moment.js, here is the fiddle link.. go check em out !

Hope this helps :)

How to use JqPlot with ASP.NET MVC ?

jqPlot is a plotting and charting plugin for the jQuery Javascript framework. jqPlot produces beautiful line, bar and pie charts with many more features.

Below is a step by step guide on how to use JqPlot with ASP.NET MVC.

Step 1 : Download and install JqPlot

You can download and install using the nuget extension for jqPlot created by Cris Leonelle as shown below or you can manually download the files from here and create a subfolder jqPlot inside your Scripts folder and copy all .js files from the jqPlot download inside this subfolder. But I prefer using the nuget extension.

enter image description here

Step 2 : Include jplot js scripts and stylesheet

Make sure to include at least the following 3 for this example.

<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>  
<script src="../../Scripts/jqPlot/jquery.jqplot.js" type="text/javascript"></script>  
<link href="../../Scripts/jqPlot/jquery.jqplot.css" rel="stylesheet" type="text/css" />  

Step 3 : Add a plot container

Add a container (target) to your web page where you want your plot to show up. Be sure to give your target a width and a height:

<div id="chartdiv" style="height:400px;width:600px; "></div>  

Step 4 : jQuery code to create a plot

$.jqplot('chartdiv', [[[1, 2],[3,5.12],[5,13.1],[7,33.6],[9,85.9],[11,219.9]]]);  

Output

<img src=” />

Step 4 : Now lets get this data from controller

Now that we have a basic understanding of how jqPlot works, I will now show how to get the values from a controller action. In the example below I am populating a list, you can fetch this data from database instead.

public ActionResult FetchGraphData()  
{  
    var data = new List<Statistics>  
    {  
        new Statistics{Day = "1-Nov-2012", Value = 10},  
        new Statistics{Day = "2-Nov-2012", Value = 20},  
        new Statistics{Day = "3-Nov-2012", Value = 22},  
        new Statistics{Day = "4-Nov-2012", Value = 15},  
        new Statistics{Day = "5-Nov-2012", Value = 40},  
        new Statistics{Day = "6-Nov-2012", Value = 1},  
        new Statistics{Day = "7-Nov-2012", Value = 0},  
        new Statistics{Day = "8-Nov-2012", Value = 3},  
        new Statistics{Day = "9-Nov-2012", Value = 11},  
        new Statistics{Day = "10-Nov-2012", Value = 22},  
        new Statistics{Day = "11-Nov-2012", Value = 33},  
        new Statistics{Day = "12-Nov-2012", Value = 44},  
        new Statistics{Day = "13-Nov-2012", Value = 44},  
        new Statistics{Day = "14-Nov-2012", Value = 44},  
        new Statistics{Day = "15-Nov-2012", Value = 44},  
    };

    var amountList = new List<int>();  
    var dayList = new List<string>();

    foreach (var item in data)  
    {  
        dayList.Add(item.Day);  
        amountList.Add(item.Value);  
    }

    return Json(new {stats=amountList, days=dayList}, JsonRequestBehavior.AllowGet);  
}

public class Statistics  
{  
    public int Value { get; set; }  
    public string Day { get; set; }  
}  

I have made an ajax call to the above action, and on success function I am plotting the graph using the data recieved. As you can see I have used the Bar Renderer for this example, for which you need to import

<script src="../../Scripts/jqPlot/plugins/jqplot.barRenderer.min.js" type="text/javascript"></script>  
<script src="../../Scripts/jqPlot/plugins/jqplot.categoryAxisRenderer.min.js" type="text/javascript"></script>  

<script type="text/javascript">  
    $(document).ready(function () {

    var url = '@Url.Action("FetchGraphData", "Home")';

    $.ajax({  
        url: url,  
        type: 'GET',  
        success: function (result) {  
        testJqPlot(result.stats, result.days);  
        },  
        error: function () {  
        }  
    });

    function testJqPlot(stats, days) {

    $.jqplot('chart1', [stats], {  
        seriesDefaults: {  
        renderer: $.jqplot.BarRenderer,  
        rendererOptions: { fillToZero: true }  
        },  
        axes: {  
        xaxis: {  
        renderer: $.jqplot.CategoryAxisRenderer,  
        ticks: days  
        },  
        yaxis: {  
        pad: 1.05,  
        tickOptions: { formatString: '$%d' }  
        }  
        }  
        });  
        } // end of TestJqPlot  
    });  
</script>

Output :

enter image description here

One more example ! In this last example I am using web api with Jqplot. You will need to import the following scripts for this to work,

<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>  
<script src="../../Scripts/jqPlot/jquery.jqplot.js" type="text/javascript"></script>  
<script src="../../Scripts/jqPlot/plugins/jqplot.barRenderer.min.js" type="text/javascript"></script>  
<script src="../../Scripts/jqPlot/plugins/jqplot.categoryAxisRenderer.min.js" type="text/javascript"></script>  
<script src="../../Scripts/jqPlot/plugins/jqplot.dateAxisRenderer.min.js" type="text/javascript"></script>  


$(document).ready(function () {  
    var dataUrl = "/api/report/GraphData";  
    $.ajax({  
    url: dataUrl,  
    type: 'GET',  
    datatype: "json",  
    contentType: 'application/json',  
    success: function (result) {

    var arr = [];  
    for (var i = 0; i < result.length; i++) {

    var date = result[i].Date;  
    var value = result[i].Value;

    arr.push([new Date(date), value]);  
    }

    var line1 = arr;  
    var plot2 = $.jqplot('chart2', [line1], {  
    title: 'Date vs Revenue',  
    axes: {  
    xaxis: {  
    renderer: $.jqplot.DateAxisRenderer,  
    tickOptions: { formatString: '%b %#d, %y' },  
    pad: 0  
    },  
    yaxis: {  
    }  
    },  
    series: [{ lineWidth: 2  
    ,markerOptions: { style: 'filledCircle', size: 0}  
    }]  
    });  
    },  
    error: function () {  
    console.log("error in ajax call");  
    }  
    });  
});  


public class ReportController : ApiController  
{  
    public List<Stats> GetGraphData()  
    {  
        List<FetchChartData_Result> data;  
        using (var context = new testEntities())  
        {  
            data = context.FetchChartData().ToList();  
        }

        var stats = new List<Stats>();

        foreach (var item in data)  
        {  
            stats.Add(new Stats {  
                            Date = item.stats_date,  
                            Value = item.customer_revenue  
                            });  
        }  
        return stats;  
        }  
    }

public class Stats  
{  
    public DateTime Date;  
    public Nullable<double> Value;  
}

enter image description here

Hope this helps :)

Further Reading:
JqPlot
JqPlot Usage Documentation
Charts with Asp.net MVC and jQuery through jqPlot
ASP.NET MVC and jQuery jqPlot sample
jqPlot bar graph with asp.net MVC 3
All in one example