Showing posts with label database. Show all posts
Showing posts with label database. Show all posts

Wednesday, June 13, 2012

Passing extra parameters with dataTable.net plugin while server paging is enabled in asp.net MVC 3 and Web form

Recently I have added two posts to implement dataTable.net jQuery plugin with server side paging with MVC3 and asp.net web form. First one is in MVC 3 and second one is in web form. We can find these two posts here-

http://growingtech.blogspot.in/2012/06/ajax-data-paging-with-datatablesnet.html
http://growingtech.blogspot.in/2012/06/ajax-data-paging-with-datatablesnet_06.html

I will request to study these two posts in sequentially to understand this one.

In this post we will be discussing how to pass additional parameters when page index changes happen in dataTable.net. To pass additional parameters in ajax paging we can use fnServerParams function of dataTable. In the MVC post we have discussed how dataTable plugin adds request parameters as querystring. And this function (fnServerParams) provides an input parameter which is nothing but an array of the query string parameters. We can do modification to the array in the function to accomodiate our need of extra parameters. Each array element in the input array is an object of the following form-
{ "name": "name of parameter/querystring", "value": "value of parameter/querystring " }
So, we can add our additional parameter accordingly. Suppose we have following input data as additional parameter-
First Criteria: <input id="txtParameter1" /><br />
Second Criteria : <input id="txtParameter2" />
We can add the these extra parameter like below-
<script type="text/javascript" charset="utf-8">
    $(document).ready(function () {
        $('#example').dataTable({
            "bServerSide": true,
            "bProcessing": true,
            "sPaginationType": "full_numbers",
            "sAjaxSource": 'Datatable Plugin Pagination Issue AjaxPath.aspx',
            "fnServerParams": function (aoData) {
                aoData.push(
                    { "name": "firstcriteria", "value": $("#txtParameter1").val() },
                    { "name": "secondcriteria", "value": $("#txtParameter2").val() }
                );
            }
        });
    });
</script>
In web form:

In web form we can access these parameters like below and use for database operations –
var firstCriteria = Request.QueryString["firstcriteria"];
var secondCriteria = Request.QueryString["secondcriteria"];
In MVC 3-

To use in MVC 3 we can modify data model like below to accommodate our new parameters-
    public class TableParameter
    {
        public string sEcho { get; set; }
        public int iDisplayStart { get; set; }
        public int iDisplayLength { get; set; }
        public string firstcriteria { get; set; }
        public string secondcriteria { get; set; }
    }
Input data will be available in the controller method to use.

Monday, April 2, 2012

Dynamic database driven jQuery Tabs in asp.net

In this post we will go through database driven, dynamic jQuery Tabs implementation. To start with lets first check how the tabs HTML looks like.

The basic structure of the HTML that is needed for Tabs implementation looks like this-
<div id="tabs">
   <ul>
      <li><a href="#tabs-1">Nunc tincidunt</a></li>
      <li><a href="#tabs-2">Proin dolor</a></li>
      <li><a href="#tabs-3">Aenean lacinia</a></li>
   </ul>
   <div id="tabs-1">
      <p>Tab 1 content</p>
   </div>
   <div id="tabs-2">
      <p>Tab 2 content</p>
   </div>
   <div id="tabs-3">
      <p>Tab 3 content</p>
   </div>
</div>
Now to implement a data base driven or a dynamic tab, we need to find some repeated sequences of content. If we analyze the HTML structure above, we can see two repeated sequences. First is the UL LI with anchor. Each LI is nothing but a repeat of the other. Only difference is the content of the anchor and the href. Secondly, the repeated sequence is the divs below UL. Only difference is the id and content of the div. So, here is another repeated sequence. So to make dynamic or database driven Tabs we, need to make the tow sets of repetitions.

Now here is a implementation using asp.net repeater control-

http://forums.asp.net/p/1693184/4474572.aspx/1?Re+how+to+interact+this+jquery+with+asp+net+codes+

In this link I am little lazy to write the database code. So I have taken the help of in memory datasource. This can be easily changed and the content can be made database driven and its left up to you. If you notice, the connection between the tab item and the content item is done through ListID. In the anchor href we have the following code href="#fragment-<%#Eval("ListID") %>". And in the div id we have id="fragment-<%#Eval("ListID") %>".

We can see another post below-

http://forums.asp.net/p/1663415/4345867.aspx/1?Re+Tabs+creation+using+Jquery+at+runtime

In this post I have created using jQuery and an array rendered to the page using ClientScript.RegisterClientScriptBlock. This also we can make database driven. We can also get the content of the Tabs using jQuery ajax and asp.net pagemethod or webmethod.

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.