Showing posts with label driven. Show all posts
Showing posts with label driven. Show all posts

Wednesday, June 6, 2012

jqPlot bar graph with asp.net MVC 3

In this post we will be exploring using jqPlot bar graph with asp.net MVC 3. We can download the plugin for the below location-

http://www.jqplot.com/

To start with let’s see how bar graph works. Following is code for a bar graph with HTML and JavaScript bar data object-
<link class="include" rel="stylesheet" type="text/css" href="@Url.Content("~/scripts/jqplot/css/jquery.jqplot.min.css")" />
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="@Url.Content("~/scripts/jqplot/excanvas.min.js")"></script><![endif]-->
<script type="text/javascript" src="@Url.Content("~/scripts/jqPlot/jquery.jqplot.min.js")"></script>
@*<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.canvasTextRenderer.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.canvasAxisTickRenderer.min.js")"></script>*@
<script type="text/javascript" src="@Url.Content("~/scripts/jqplot/jqplot.categoryAxisRenderer.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/jqPlot/jqplot.barRenderer.min.js")"></script>

<div class="example-content">
    <!-- Example scripts go here -->
    <style type="text/css">
        .jqplot-target
        {
            margin: 30px;
        }
        .tooltipCss
        {
            position: absolute;
            background-color: #b2b1ac;
            color: White;
            z-index: 200;
            padding: 5px;
            border-radius: 5px;
            display: none;
        }
    </style>
    <div id="chart2" class="plot" style="width: 760px; height: 360px;">
    </div>
</div>
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        pop1980 = [4, 5, 3, 6, 5, 4, 2, 5];
        pop1990 = [3, 5, 6, 2, 4, 3, 4, 6];
        pop2000 = [2, 5, 6, 3, 4, 5, 2, 4];
        pop2008 = [5, 3, 4, 2, 6, 5, 2, 4];

        ticks = [5, 6, 7, 8, 9, 10, 11, 12];

        series = [
                  { label: 'r. DMR Published - Singapore' },
                  { label: 's. DMR Published - London' },
                  { label: 't. DMR Published - Houston' },
                  { label: 'u. DMR Published - Global' }
               ];

        plot2 = $.jqplot('chart2', [pop1980, pop1990, pop2000, pop2008], {
            legend: {
                show: true,
                placement: 'outsideGrid'
            },
            seriesDefaults: {
                renderer: $.jqplot.BarRenderer,
                rendererOptions: {
                    barPadding: 5
                }
            },
            series: series,
            axes: {
                xaxis: {
                    renderer: $.jqplot.CategoryAxisRenderer,
                    ticks: ticks
//                    ,
//                    tickRenderer: $.jqplot.CanvasAxisTickRenderer,
//                    tickOptions: {
//                        angle: -15
//                    }
                }
            }
        });
        $('#chart2').bind('jqplotDataMouseOver',
            function (ev, seriesIndex, pointIndex, data) {
                $('#info2').html('series "' + series[seriesIndex].label + '" point "' + (pointIndex + 5) + '"<br /> value "' + data[1] + '"');
                $('#info2').css({ "left": ev.pageX + 3, "top": ev.pageY })
                $('#info2').show();
            }
        );
        $('#chart2').bind('jqplotDataUnhighlight',
            function (ev) {
                $('#info2').hide();
            }
        );
    });
</script>
<div id="info2" class="tooltipCss">
</div>
If you check the file references, you can check a file named excanvas.min.js. This is the file for internet explorer less than 9. As the bar is rendered in canvas, a HTML 5 feature, which is not supported in lower versions of IE. All other files are required for bar graph. If you notice, you can see there are two files that are commented out (jqplot.canvasTextRenderer.min.js and jqplot.canvasAxisTickRenderer.min.js ). These two files are needed if you want to rotate the tick texts in both the axis. In the bar initialization you can find the corresponding tickRenderer code is commented out for x-axis. Div with id chart2 is used to hold the bar graph. And div with id info2 is used to hold tooltip content. Input to the graph is array of arrays where each inner array represents data for each bar.

Number of items in each inner array is same. Other than this array there are two more arrays used. One is ticks, this is used to represent the data interval in x- axis. And another is series, this array is used to represent the name of each bar. The order of the series item should be same as the order of the data input arrays.

There are many options used in the plugin. Detail of various options can be found here-

http://www.jqplot.com/docs/files/jqPlotOptions-txt.html
http://www.jqplot.com/docs/files/optionsTutorial-txt.html

We can use as many options required in this case.

Other than these we are using two more events in the plugin named 'jqplotDataMouseOver' and 'jqplotDataUnhighlight'. We are using these events to track tooltips in each bar. We can add debugger and check what is happening.

Model driven Bar Graph:

To make the graph model driven we can have the following model-
namespace Bar.Models
{
    public class BarViewModel
    {
        public int Id { get; set; }
        public string BarName { get; set; }
        public int[] Values { get; set; }
    }
    public class BarDataViewModel
    {
        public int[] TickValues { get; set; }
        public List<BarViewModel> Data { get; set; }
    }
}
And in the controller action we are creating the data in memory as –
        public ActionResult ModelDrivenBar()
        {
            BarDataViewModel data = new BarDataViewModel();
            data.Data = new List<BarViewModel>();
            BarViewModel bar;
            Random r=new Random();
            for (int i = 0; i < 4; i++)
            {
                bar = new BarViewModel();
                bar.Id = i;
                bar.BarName = "Bar Name " + i.ToString();
                bar.Values = new int[10];
                for (int j = 0; j < 10; j++)
                    bar.Values[j] = r.Next(2, 6);
                data.Data.Add(bar);
            }
            data.TickValues = new int[10];
            for (int i = 5; i < 15; i++)
                data.TickValues[i - 5] = i;
            return View(data);
        }
We need to do two changes in the view to accommodate the changes. First add the following line at the starting of the view-
@model Bar.Models.BarDataViewModel
And secondly generate the three arrays, as we have discussed earlier, like below-
        var data = new Array();
        var ticks = new Array();
        var series = new Array();
        @foreach (var d in Model.TickValues)
        {
            <text>ticks.push(</text>@d<text>);</text>
        }
        @foreach (var d in Model.Data)
        {
            <text>var bar</text>@d.Id<text>= new Array();</text>
            <text>series.push({label : "</text>@d.BarName<text>"});</text>
            foreach (var darray in d.Values)
            { 
                <text>bar</text>@d.Id<text>.push(</text>@darray<text>);</text>
            }
            <text>data.push(bar</text>@d.Id<text>);</text>
        }
        plot2 = $.jqplot('chart2', data, {
Instead of explaining the code above, we can check the output of the code below-
        var data = new Array();
        var ticks = new Array();
        var series = new Array();
            ticks.push(5);
            ticks.push(6);
            ticks.push(7);
            ticks.push(8);
            ticks.push(9);
            ticks.push(10);
            ticks.push(11);
            ticks.push(12);
            ticks.push(13);
            ticks.push(14);
            var bar0= new Array();
            series.push({label : "Bar Name 0"});
                bar0.push(2);
                bar0.push(4);
                bar0.push(5);
                bar0.push(5);
                bar0.push(4);
                bar0.push(3);
                bar0.push(2);
                bar0.push(2);
                bar0.push(3);
                bar0.push(5);
            data.push(bar0);
            var bar1= new Array();
            series.push({label : "Bar Name 1"});
                bar1.push(4);
                bar1.push(2);
                bar1.push(2);
                bar1.push(5);
                bar1.push(2);
                bar1.push(3);
                bar1.push(4);
                bar1.push(5);
                bar1.push(5);
                bar1.push(2);
            data.push(bar1);
            var bar2= new Array();
            series.push({label : "Bar Name 2"});
                bar2.push(4);
                bar2.push(3);
                bar2.push(3);
                bar2.push(4);
                bar2.push(2);
                bar2.push(2);
                bar2.push(2);
                bar2.push(3);
                bar2.push(4);
                bar2.push(5);
            data.push(bar2);
            var bar3= new Array();
            series.push({label : "Bar Name 3"});
                bar3.push(5);
                bar3.push(4);
                bar3.push(5);
                bar3.push(2);
                bar3.push(4);
                bar3.push(3);
                bar3.push(5);
                bar3.push(4);
                bar3.push(3);
                bar3.push(5);
            data.push(bar3);
        plot2 = $.jqplot('chart2', data, {
What we are doing here is just creating the bar data dynamically by looping the model data.

Ajax Bar Graph:

To make it ajax driven we can simply change the controller return type like below-
        public JsonResult AjaxBarData()
        {
            //same code like earlier
            return Json(data,JsonRequestBehavior.AllowGet);
        }
And we can do an ajax call to the controller and in the success of the ajax call we can initialize the graph-
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "get",
            timeout: 30000,
            url: '@Url.Action("AjaxBarData")',
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                var data = new Array();
                var ticks = new Array();
                var series = new Array();
                $(result.TickValues).each(function (i, itm) {
                    ticks.push(itm);
                });
                $(result.Data).each(function (i, itm) {
                    series.push({ label: itm.BarName });
                    data[i] = new Array();
                    $(itm.Values).each(function (j, item) {
                        data[i].push(item);
                    });
                });
  //initialize the bar graph here
                plot2 = $.jqplot('chart2', data, {
            },
            error: function (req, status, error) {
                debugger;
            }
        });
    });
</script>
That’s all. You can download the bar code here.

Thursday, March 22, 2012

Full calendar - saving event using ajax / pagemethod/ webmethod in asp.net

In this post we will be saving the event in a full calendar plugin using jQuery ajax and asp.net pagemethod or web service. To go through the post I request you to first check the following post. We are going the proceed forward with the same post and its source code.

http://growingtech.blogspot.in/2012/02/full-calendar-with-json-data-source.html

In addition to the previous script and CSS file references, we have added one more script file for this purpose-
<script src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js" type="text/javascript"></script>
This file is used hare to to JSON stringify the event object.

Now how we are going to solve this issue is that on click of a day, we are going popup an entry form for the event and we will use ajax to save the event to the server and after successful saving we will be adding the event to the calender. Now calender plugin has some event to solve this purpose-
  1. dayClick - this event happen during the mouse click of a day.
  2. renderEvent - using this event we can add an event to the calender. We can set stick to true to permanently add the event to the calender.
For popup we are going to use jQuery dialog. For adding the event we can add the following HTML-
<div id="eventToAdd" style="display: none; font-size: 12px;">
    Event name:
    <input id="eventName" type="text" /><br />
    Event start date:
    <input id="eventStartDate" type="text" />(MM-dd-yyyy)<br />
    Event end date:
    <input id="eventEndDate" type="text" />(MM-dd-yyyy)<br />
</div>
Now we need to show popup dialog for adding event on the day click of the calendar day. To do so we will take the help of the dayClick event of the calender and it goes here-
<script type="text/javascript">
    $('div[id*=fullcal]').fullCalendar({
        dayClick: function (dateSelected, allDay, jsEvent, view) {
            $("#eventToAdd").dialog(
            {
                title: "Add event",
                modal: true,
                buttons: {
                    "Add": function () {
                       //event adding logic goes here                 
                    }
                }
            });
        }
    });
</script>
Now on click of add button in the dialog we need to do two things. First save the event data using jQuery ajax and page method / web service. And secondly on the success of the ajax call add the event on the calender. Both the work is done here-
"Add": function () {
    var event = new Object(), eventToSave = new Object(); ;
    eventToSave.EventID = event.id = Math.floor(200 * Math.random());
    event.start = new Date($("#eventToAdd #eventStartDate").val());
    eventToSave.StartDate = $("#eventToAdd #eventStartDate").val();
    if ($("#eventToAdd #eventEndDate").val() == "") {
        event.end = event.start;
        eventToSave.EndDate = eventToSave.StartDate;
    }
    else {
        event.end = new Date($("#eventToAdd #eventEndDate").val());
        eventToSave.EndDate = $("#eventToAdd #eventEndDate").val();
    }
    eventToSave.EventName = event.title = $("#eventToAdd #eventName").val();

    $("#eventToAdd input").val("");
    $.ajax({
        type: "POST",
        contentType: "application/json",
        data: "{eventdata:" + JSON.stringify(eventToSave) + "}",
        url: "FullcalenderwithPagemethod.aspx/AddEvents",
        dataType: "json",
        success: function (data) {
            $('div[id*=fullcal]').fullCalendar('renderEvent', event, true);
            $("#eventToAdd").dialog("close");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            debugger;
        }
    });
}
What we are doing here is in line 2 we are creating two JavaScript objects event and eventToSave and line 3-14 we are assigning the values from the popup. And finally we are saving the data to server using ajax call. Why we have taken two objects here is event data of the calender has different property name and the server event have different name. Once the saving of event is successful we are adding the event object to the calendar using line number 24. The page method using for this is as follows-
[System.Web.Services.WebMethod]
public static bool AddEvents(Event eventdata)
{
    List events;
    if (HttpContext.Current.Session["events"] != null)
        events = (List)HttpContext.Current.Session["events"];
    else
        events = new List();
    events.Add(eventdata);
    HttpContext.Current.Session["events"] = events;
    return true;
}
For this example we have used in memory event object. We can easily replace it with proper database driven. The complete modified code for this is available here for download.

Monday, March 19, 2012

Dynamic galleriffic using pagemethod / webmethod in asp.net

In this post we are going to explore using Galleriffic jQuery plugin with asp.net web method/page method /web service. Also we will see how to change the image source dynamically. The detail of the plugin available here. First lets quickly go through the plugin usage-

First of all we need to add the following script files for working with Galleriffic-
<link rel="stylesheet" href="http://www.twospy.com/galleriffic/css/basic.css" type="text/css" />
    <link rel="stylesheet" href="http://www.twospy.com/galleriffic/css/galleriffic-2.css"
        type="text/css" />
    <script type="text/javascript" src="http://www.twospy.com/galleriffic/js/jquery-1.3.2.js"></script>
    <script type="text/javascript" src="http://www.twospy.com/galleriffic/js/jquery.galleriffic.js"></script>
    <script type="text/javascript" src="http://www.twospy.com/galleriffic/js/jquery.opacityrollover.js"></script>
The opacityrollover js file is optional. And also if we want we can define our own CSS files.

The HTML needed for the plugin is as follows-
<div id="container">
    <div id="gallery" class="content">
        <div id="controls" class="controls">
        </div>
        <div class="slideshow-container">
            <div id="loading" class="loader">
            </div>
            <div id="slideshow" class="slideshow">
            </div>
        </div>
        <div id="caption" class="caption-container">
        </div>
    </div>
    <div id="thumbs" class="navigation">
        <ul class="thumbs noscript" id="containerID">
            <li>
                <a class="thumb" name="drop" href="http://www.gallery2c.com/admin/Upload/FullImage/moda01.jpg"
                    title="Title #1">
                    <img src="http://www.gallery2c.com/admin/Upload/ThumbNail/moda01.jpg" alt="Title #1" />
                </a>
                <div class="caption">
                    Any html can be placed here ...
                </div>
            </li>
            .
            .
            .
            .
            .
        </ul>
    </div>
    <div style="clear: both;">
    </div>
</div>
Lets explain the HTML a little more. Line 3-4 is used for adding buttons of the slideshow(Play/Stop slideshow, Next image, previous image). Line 5-10 is used for showing the big image where line 6-7 is used to show the loading effect while the image is getting loaded and line 8-9 is used to show the actual image. And line 11-12 is used to show any additional information for the image. And the line 14-30 is used to add the image information. In that UL represent the image container. And each LI correspond to a image. It contains many information. Image tag in the LI represent the thumbnail image and the href of the container anchor represent the image that will be shown as a big image. Finally the div with class caption can be used as a container of additional information. The additional information can be of type HTML.

We are also going to use an additional select box as an option to change the data source for the plugin. The code goes here-
<select id="changeGallery">
    <option value="gett" selected="selected">Gallery 1</option>
    <option value="moda">Gallery 2</option>
</select>
Now to activate the plugin with rollover we call use the following code block-
var onMouseOutOpacity = 0.67;
$('#thumbs ul.thumbs li').opacityrollover({
    //add all option here
});

// Initialize Advanced Galleriffic Gallery
var gallery = $('#thumbs').galleriffic({
    //add all option here
});
So for enabling the Galleriffic we are going to use the following code-
function attachGallery() {
    var onMouseOutOpacity = 0.67;
    $('#thumbs ul.thumbs li').opacityrollover({
        mouseOutOpacity: onMouseOutOpacity,
        mouseOverOpacity: 1.0,
        fadeSpeed: 'fast',
        exemptionSelector: '.selected'
    });

    galleryVar = $('#thumbs').galleriffic({
        delay: 2500,
        numThumbs: 15,
        preloadAhead: 10,
        enableTopPager: true,
        enableBottomPager: true,
        maxPagesToShow: 7,
        imageContainerSel: '#slideshow',
        controlsContainerSel: '#controls',
        captionContainerSel: '#caption',
        loadingContainerSel: '#loading',
        renderSSControls: true,
        renderNavControls: true,
        playLinkText: 'Play Slideshow',
        pauseLinkText: 'Pause Slideshow',
        prevLinkText: '&lsaquo; Previous Photo',
        nextLinkText: 'Next Photo &rsaquo;',
        nextPageLinkText: 'Next &rsaquo;',
        prevPageLinkText: '&lsaquo; Prev',
        enableHistory: false,
        autoStart: false,
        syncTransitions: true,
        defaultTransitionDuration: 900,
        onSlideChange: function (prevIndex, nextIndex) {
            this.find('ul.thumbs').children()
     .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
     .eq(nextIndex).fadeTo('fast', 1.0);
        },
        onPageTransitionOut: function (callback) {
            this.fadeTo('fast', 0.0, callback);
        },
        onPageTransitionIn: function () {
            this.fadeTo('fast', 1.0);
        }
    });
}
Now to implement the dynamic Galleriffic, lets remove all the LI's form the UL container. And let add a hidden block of LI that we will be using as a template. The code block is as follows-
<div id="itemContainer" style="display: none">
    <li><a class="thumb" name="drop" href="http://www.gallery2c.com/admin/Upload/FullImage/moda01.jpg"
        title="Title #1">
        <img src="http://www.gallery2c.com/admin/Upload/ThumbNail/moda01.jpg" alt="Title #1" />
    </a>
        <div class="caption">
            Any html can be placed here ...
        </div>
    </li>
</div>
Now to make it database driven we need to do the following-
  1. Clone the hidden LI
  2. Change HREF and TITLE of the anchor tag using database values
  3. Change SRC and ALT of the image tag using database values
  4. Change the caption div inner HTML with database value
  5. Append the cloned LI to the container UL
  6. Repeat the process for all images
Now let us have some asp.net page method or web method that will return images that need to be added dynamically. It goes here-
[WebMethod]
public static object GetImageDetail(string id)
{
    var imageData = new { ImageID = 0, URL = string.Format("http://www.gallery2c.com/admin/Upload/FullImage/{0}01.jpg",id), Thumb = string.Format("http://www.gallery2c.com/admin/Upload/ThumbNail/{0}01.jpg",id), Title = "Title 0", Caption = "Caption 0" };
    var imageDataList = (new[] { imageData }).ToList();
    for (int i = 2; i < 10; i++)
        imageDataList.Add(new { ImageID = 0, URL = string.Format("http://www.gallery2c.com/admin/Upload/FullImage/{0}0{1}.jpg", id, i), Thumb = string.Format("http://www.gallery2c.com/admin/Upload/ThumbNail/{0}0{1}.jpg", id, i), Title = string.Format("Title {0}", i), Caption = string.Format("Caption {0}", i) });
    for (int i = 10; i < 20; i++)
        imageDataList.Add(new { ImageID = 0, URL = string.Format("http://www.gallery2c.com/admin/Upload/FullImage/{0}{1}.jpg", id, i), Thumb = string.Format("http://www.gallery2c.com/admin/Upload/ThumbNail/{0}{1}.jpg", id, i), Title = string.Format("Title {0}", i), Caption = string.Format("Caption {0}", i) });
    return imageDataList;
} 
Here I have taken the help of Gallery2c.com for images. And the jQuery code used to dynamically load the images goes here-
var templete, containerVar;
jQuery(document).ready(function ($) {
    templete = $("#itemContainer li");
    containerVar = $("#containerID");
    getData();
});
function getData() {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        data: "{id:'gett'}",
        url: "Clear ALL images in the Galleriffic jquery plugin and Insert new images using jquery or javas.aspx/GetImageDetail",
        dataType: "json",
        success: function (data) {
            $(data.d).each(function (i, item) {
                containerVar.append(templete.clone());
                containerVar.find("li:last a.thumb").attr({ "href": item.URL, "Title": item.Title });
                containerVar.find("li:last a.thumb img").attr({ "src": item.Thumb, "Title": item.Title });
                containerVar.find("li:last .caption").html(item.Caption);
            });
            attachGallery();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            debugger;
        }
    });
    $('div.navigation').css({ 'width': '300px', 'float': 'left' });
    $('div.content').css('display', 'block');
}
And to dynamically change the datasource in the plugin we can call the getData() method on the change of the previously added dropdown. The code is as below-
$("#changeGallery").change(getData);
And also we need to remove the content of the container UL before changing the content of the UL. So, at the start of the getData() method we can append the code containerVar.empty();. But there is a small problem, if we play the slide show and then change the dropdown selection. Then the slide show shows wrong image in the big image. It shows the previous datasource images. So, before changing the data source we can stop the slide show and then change the source. The final code looks like-
        var templete, containerVar;
        jQuery(document).ready(function ($) {
            templete = $("#itemContainer li");
            containerVar = $("#containerID");
            getData();
            $("#changeGallery").change(getData);
        });

        function getData() {
            try {
                galleryVar.pause();
            }
            catch (ex) {
            }
            containerVar.empty();
            $.ajax({
                type: "POST",
                contentType: "application/json",
                data: "{id:'" + $("#changeGallery").val() + "'}",
                url: "Clear ALL images in the Galleriffic jquery plugin and Insert new images using jquery or javas.aspx/GetImageDetail",
                dataType: "json",
                success: function (data) {
                    $(data.d).each(function (i, item) {
                        containerVar.append(templete.clone());
                        containerVar.find("li:last a.thumb").attr({ "href": item.URL, "Title": item.Title });
                        containerVar.find("li:last a.thumb img").attr({ "src": item.Thumb, "Title": item.Title });
                        containerVar.find("li:last .caption").html(item.Caption);
                    });
                    attachGallery();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    debugger;
                }
            });
            $('div.navigation').css({ 'width': '300px', 'float': 'left' });
            $('div.content').css('display', 'block');
        }
You can download the code form here.