Archive

Posts Tagged ‘jquery’

Have a toast with toastr.js

February 28, 2014 Leave a comment

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.

BundleConfig.cs

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));

        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js","~/Scripts/toastr.js",
                  "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css","~/Content/toastr.css",
                  "~/Content/site.css"));
    }
}

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

Index.cshtml

    <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>
            <div class="col-md-3">
                <h3>Toastr Information</h3>
                <p><a id="toastr-info" class="btn btn-info">Information</a></p>
            </div>
            <div class="col-md-3">
                <h3>Toastr Warning</h3>
                <p><a id="toastr-warning" class="btn btn-warning ">Warning</a></p>
            </div>
            <div class="col-md-3">
                <h3>Toastr Error</h3>
                <p><a id="toastr-error" class="btn btn-danger">Error</a></p>
            </div>
        </div>

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 () {
            toastr.info('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.')
        });
    });
</script>

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.

Contact.cs

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

ContactController.cs

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.

Index.aspx

<%@ Page Title="" Language="C#" 
         MasterPageFile="~/Views/Shared/Site.Master" 
         Inherits="System.Web.Mvc.ViewPage<JQueryTemplate.Models.Contact>" %>

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

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

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

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

        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() {
            $(resultList).empty();
        };

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

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

    </script>

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

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.

[OutputCache(Duration=60,VaryByParam="")]
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 http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js.

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

</div>

 

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 http://docs.jquery.com/Plugins/validation

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

</div>

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:

Sydney WebCamp Wrap Up

June 9, 2010 2 comments

A nice wrap of the Sydney WebCamp by Catherine Eibner. It was good to hear that Scott Hanselman and James Senior both acknowledged that Sydney Webcamp was the best.

It was a huge success in its opening year and i hope it becomes even bigger in coming years :)

Race Day Commander – Project Setup

I have been very busy with lot of stuff and haven’t been able to focus on the “Race Day commander” project, in fact the day we  put the prototype in codeplex we haven’t had chance to even look at it.

It was good that one of my mates downloaded the project and reported that he had some problems in running the project.I knew what the problem could be and thought I will write a few instruction on how to setup the project.

So here is how you can make at least the project up and running while we work on adding real bits to make it a real-life application.

  1. Download the database file(.bak) and the VS solutions file from here.
  2. Restore it in your SQLExpress database and the name the database as RDC.
  3. Change the connection string in both web.config files i.e. RDC.Admin & RDC.Web project, right now it says BART_PC\SQLExpress and change it to .\SQLExpress.
  4. Run the project and browse to http://localhost:22676/Event/Index/1 as the default routing takes you the home index page and we haven’t fixed it yet.
  5. Open a new instance of your browser and browse to http://localhost:32124/Comments/List.aspx and add comments. This is the dynamic data page which we tried to demonstrate during the demo.
  6. Enter a few sentences in the comment field and enter todays date time in format dd/mm/yy hh:mn:ss so that the comments get added as the latest comment.
  7. Flip back to the main application and you will see the comment appearing automatically.

In upcoming days i will start blogging into “deep dive” kind of stuff, meanwhile any feedback or comment is most welcome.

Race Day Commander
Race Day Commander with comments

JQuery template

June 2, 2010 1 comment

One of the coolest thing in “Race day commander” application is the use of JQuery template. In fact in our work place we have been using the open source “Jtemplate” plugin for quite sometime and it is a a great templating plugin. But at the #webcamp James Senior told us about the microsoft JQuery template and it was fun to use it.

The plugin is available at http://github.com/nje/jquery-tmpl and of course to learn it refer to Scott Gu’s blog.

For us, it was literally changing the ‘#’ character to ‘{‘ and hit refresh :-).

For Example in JTemplate it is:-

<div>
{# CommentText.substr(0,250) }
{#if CommentText.length > 250}<span>… more</span>
{#/if}
</div>

And in JQuery template it would be:-

<div>
{{= CommentText.substr(0,250) }}
{{if CommentText.length > 250}}<span>… more</span>
{{/if}}
</div>

This is really a cool way of making your page interactive and implementing “progressive disclosure” logic by having a template in the page and return tiny json objects and is not limited to ASP.NET MVC, in fact I use it a lot in my webforms which still have UpdatePanels ( Urrggghhh !!! )

Race Day Commander !!

June 1, 2010 1 comment

This is the“Race day Commander” app which Anthony and I build at the Sydney web camp, thanks to Anthony who finally put in on codeplex and looking forward for feedback and contribution.

Some of the key features of this projects are:-

  • ASP.Net MVC (using areas)
  • Dynamic Data (used for rapid admin system generation)
  • EF4 for Data Access (using SQL Express)
  • Asset Management (using telerik ASP.Net MVC controls)
  • AJAX (using jQuery)
  • Live updates (using jQuery)
  • Client side HTML rendering (using jQuery templates)
  • Strongly typed references (using T4MVC)
  • Error reporting (using Elmah)
  • JavaScript Graphs and Charts (using Raphael)
  • CSS3 (for styling)
  • View Models
  • Mobile Support (using custom view engine)
  • Compression (using gzip)
  • Typed App Config Access
Follow

Get every new post delivered to your Inbox.

Join 41 other followers