Archive for the ‘JQuery’ Category

Have a toast with toastr.js

February 28, 2014 2 comments

In this post I am going to talk about a very simple notification jQuery plugin call toastr and I believe not many people have heard about it.

It is relatively simple to use and I often use it as debugging tool when I am writing JQuery plugin or trolling through JavaScript code.

Lets get started with a new ASP.NET MVC project and nuget the package with the following command.

PM> Install-Package toastr


The nuget package will add the css and the JavaScript file to the Asp.Net MVC project and we need to wire up the toastr.css and the toastr.js in our bundle config as shown below.


public class BundleConfig
    public static void RegisterBundles(BundleCollection bundles)
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(

        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(

        bundles.Add(new StyleBundle("~/Content/css").Include(

Now I’m going to create a simple page with 4 buttons showing characteristics of toastr notification functionality.


    <div class="jumbotron">
        <div class="row">
            <div class="col-md-3">
                <h3>Toastr Success</h3>
                <p><a id="toastr-success" class="btn btn-success">Success</a></p>
            <div class="col-md-3">
                <h3>Toastr Information</h3>
                <p><a id="toastr-info" class="btn btn-info">Information</a></p>
            <div class="col-md-3">
                <h3>Toastr Warning</h3>
                <p><a id="toastr-warning" class="btn btn-warning ">Warning</a></p>
            <div class="col-md-3">
                <h3>Toastr Error</h3>
                <p><a id="toastr-error" class="btn btn-danger">Error</a></p>

In the below JavaScript code I am setting some of the toastr option like the position of the popup and wiring up the button click to the toastr notification function.

<script type="text/javascript">
    $(document).ready(function () {
        toastr.options = {
            "closeButton": true,
            "positionClass": "toast-bottom-full-width",
            "onclick": null,
            "showDuration": "0",
            "hideDuration": "0",
            "timeOut": "0",
            "showMethod": "fadeIn"
        $('#toastr-success').click(function () {
            toastr.success('This is a success notification from toastr.')

        $('#toastr-info').click(function () {
  'This is an information notification provided by toastr.')

        $('#toastr-warning').click(function () {
            toastr.warning('This is a warning notification provided by toastr.')

        $('#toastr-error').click(function () {
            toastr.error('This is an error notification provided by toastr.')

The JavaScript code is pretty straight forward and there are other options you can set such as whether a user interaction is required or not on the pop-up, do you need to call another function as part of post processing etc.

And here is the final page in action and for demonstration purpose I have taken the screenshot of all the notification in one page.

Have a toast with toastr

and here is what it would look like in a mobile device.

Have a toast with toastr - Mobile View

Happy toasting !!!


JQuery Template

March 3, 2011 2 comments

One of the reasons I started blogging was to document my project and learning experiences while working on complex problems. Right from the beginning of my career I was good in writing quick prototypes and small end-to-end proof of concepts, but what I was really not good at was the ability to remember it after sometime. So that way my blog is becoming my software repository and I am glad that it helping other guys who are about to use a particular technology or design principle.

In today’s post I am going to talk about JQuery Template although I did mention briefly about it in my previous post a 8 months ago. But this time I am going to show a full end to end solution and some tips.

The powerful thing about JQuery template is that the template runs in the browser (i.e. on client side) and hence you are taking the client CPU in order to process the template, it’s also better than using string concatenation server side and building HTML string.

So I am going to show a simple list of contact i.e Full name,Age,Phone and some sort of description and our contact class looks like this.


public class Contact
    public string Name { get; set; }
    public int Age { get; set; }
    public string Phone { get; set; }
    public string Description { get; set; }

    public Contact(string name,int age,string phone,string description)
        Name = name;
        Age = age;
        Phone = phone;
        Description = description;

and the controller


public class ContactController : Controller
    public JsonResult GetContacts()
        List<Contact> contacts = new List<Contact>()
            new Contact("Joe Blogg",29,"02-6290-0011","A good fellow"),
            new Contact("James Weathers",39,"02-6290-0012","An intelligent fellow"),
            new Contact("John Smith",49,"02-6290-0013","A very wise fellow")
        }; // Just for the demo

        return Json(contacts, JsonRequestBehavior.AllowGet);

The reason for returning a JSONResultSet is to show you guys how we can use JQuery to invoke the controller action. Lets see how the view looks like.


<%@ Page Title="" Language="C#" 
         Inherits="System.Web.Mvc.ViewPage<JQueryTemplate.Models.Contact>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript">

        var templateName = "contactTemplate";
        var resultList = "#contactList";

        $(document).ready(function () {
            $("#jq-getData").click(function () {

        function showContacts() {
            $.getJSON("/Contact/GetContacts", function (data) {
                var markup = getMarkup();
                loadTemplate(templateName, markup);

        function getMarkup() {
            var markup = "<tr><td colspan=’2′ title=’${Description}’>${Name}</td><td>Age: ${Age}</td><td>Phone: ${Phone}</td></tr>";
            return markup;

        function clearResultList() {

        function loadTemplate(templateName, markup) {
            $.template(templateName, markup);

        function applyTemplate(data) {
            $.tmpl(templateName, data).appendTo(resultList);


    <input type="button" id="jq-getData" value="Click" />
    <table><tbody id="contactList"></tbody></table

Okay that looks bit lengthy code and I will try to break it down, I will start with the main function showContacts as it is main method which orchestrate other methods.

1. Get Json data for contacts by invoking the GetContacts action on the controller.

2. Get the markup (html template).

3. Clear the Dom element which will hold the output before any processing.

4. Load the template with the template name and assign the markup to it.

5. Apply the template.

As far as writing the template is concern it’s pure html tags and mark each place holders with the “${attribute}” pattern. The important thing is that the attributes in the template placeholder has to match the property of attribute of your JSON object.Lets run the application and see how it renders on the browser.

Result output

Nothing special as you can see the JSON object has the same attribute as it was in the template markup and the template engine was able to map it and process the html. Lets take a look into the caching headers send by the web server when we requested this JSON object.

Result output

As you can see “Last modified” and “Last fetched” are showing the current time but the “Expiry” header is showing a back date of “1970”, this means that every time the page is refreshed or loaded it will request the JSON over and over again and it can impact on your website performance and scalability. Lets fix it by providing some caching into this request by adding and Output Cache directive to the GetContacts action.

public JsonResult GetContacts()
    List<Contact> contacts = new List<Contact>()
        new Contact("Joe Blogg",29,"02-6290-0011","A good fellow"),
        new Contact("James Weathers",39,"02-6290-0012","An intelligent fellow"),
        new Contact("John Smith",49,"02-6290-0013","A very wise fellow")

    return Json(contacts, JsonRequestBehavior.AllowGet);

After this build the solution and request the page again and you will see the expiry headers are added to the response and now the page will be cached on the browser for a minute.

Result output

That’s it for today and I hope you guys will find this end-to-end JQuery Template solution useful for your projects.BTW the Jquery template is available from Microsoft CDN site at

HTML Atrributes in MVC 2

October 22, 2010 Leave a comment

Recently I was working with a very interesting form problem and MVC 2, anyway I manage to solve the problem and wanted to use jQuery validation plugin. I knew i had use the htmlattributes property to inject the attributes and this is how it is done.


<div class="editor-field">

    <%: Html.TextBoxFor(model => model.Date, new {size = 25}) %>

    <%: Html.ValidationMessageFor(model => model.Date)%>



So here we are saying to the MVC View engine is that when the textbox for the Date field is generated add size as an html attribute with a value of 25,and this is how the output looks in Firebug.

So far so good and now I wanted to use JQuery Validation plugin to validate the date textbox before I submit the form. This is how JQuery validation plugin does a automatic validation of a form.

This is direct code from the Jquery validation plugin page which is at

However when i tried using the class reserved as a htmlattribute I got a clueless runtime error as “CS1513: } expected” and after some mucking around I came to know that you have to use @class instead of class . So when i change my code to this ..

<div class="editor-field">

    <%: Html.TextBoxFor(model => model.Date, new {@class = "required"}) %>

    <%: Html.ValidationMessageFor(model => model.Date)%>


and as you can see we got what we wanted:)

JQuery Snippets

August 12, 2010 1 comment

If you are web developer or thinking into moving to the lighter side (with a pun 😉 ) then you simply can’t ignore JQuery and in my personal opinion invest some time and energy into it and it will pay you off in the long run.

A couple of weeks ago I blogged about the free JQuery ebook and I also blogged about how to roll out your own code snippet using the code snippet designer.

This post is about the jQuery snippets which I think is a great way of learning jQuery syntax. You can download it from here. Once it’s downloaded unzip the file, run the msi and complete the installation.

Before we start using the snippets lets browse to the “Documents\Visual Studio 2010\Code Snippets\Visual Web Developer” folder and as you can see there are two folders “My HTML Snippet” and “My JScript Snippets”.

Under “HTML Snippets” folder

Under the HTML Snippets folder

Under JScript Snippets” folder

Under JScript Snippets folder

If you open one of these snippet files you can see it is quite similar to what we did using the snippet designer and shows the full potential of using snippets in your own development environment.

Lets start using the snippets and get some jquery code in our page. Below is a simple html page and when we type the keyword “jq”

Just type in jq

and when we hit tab twice the snippet generates the base jquery code, it’s that simple.

Code generated by the snippet

Now it’s not too scary to get use to of jQuery syntax .

Free JQuery ebook

July 13, 2010 2 comments

Even though the world cup is over and some of us are feeling sad that it got over so soon, here is a something to cheer about. Yes it’s true a free jquery ebook provided by sitepoint just because Spain won the world cup 🙂 . Just enter your email and the link to the book will send to your email and there are some free videos to learn about other technologies too.

Categories: JQuery Tags: