Friday, August 1, 2014

jqGrid with Add,Edit and Delete options in asp.net

jqGrid is a powerful plugin to display data as grid layout and Add,edit ,delete records.I had some free time so I thought to explore some features of jqGrid.
Our final Output will be :


Ok,Lets assume We have to show employee data in jqGrid  using webmethod from database (sql server)

First create a employee table :
 Table :employeeTable
Column Name
Data Type
employeeId
int
name
nvarchar(500)
email
nvarchar(200)
pwd
nvarchar(8)
phone
nchar(10)
nationalityId
int
dateOfBirth
date

Another table is :nationalTable

Column Name
Data Type
nationalId
int
natiionName
nvarchar(200)

Now create a procedure to get data from database to show the employee records:

CREATE PROC [dbo].[fetchemployeeData]
AS
 SELECT employeeId,name,email,pwd,phone                                  ,B.nationalId,CONVERT(VARCHAR(10),
         dateOfBirth,103)AS dateOfBirth,B.natiionName  FROM       employeeTable
  A JOIN nationalTable B ON A.nationalityId=B.nationalId  ORDER BY name 

Now lets work on jqGrid.
On the aspx page first add the jqGrid references as below inside the head tag:

<script src="JQGridReq/jquery-1.9.0.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script src="JQGridReq/grid.locale-en.js" type="text/javascript"></script>
    <script src="JQGridReq/jquery.jqGrid.js" type="text/javascript"></script>
    <link href="JQGridReq/ui.jqgrid.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/json2.js" type="text/javascript"></script>

Inside the form take table and div as below:
<table id="list"></table> <%--for grid--%>
<div id="pager"> </div> <%--for paging--%>


Now In the script block copy paste the below code

<script type="text/javascript">

$.ajax({
     type: "POST",
     contentType: "application/json",
     data: "{}",
     url: "jqgridexample.aspx/getEmployee",
     dataType: "json",
     success: function (data) {
        data = data.d;
        $("#list").jqGrid({
          datatype: "local",
colNames: ['Employee Id', 'Name', 'Email', 'Phone', 'Password', 'Nationality', 'Date of Birth'],
colModel: [
       { name: 'employeeId', index: 'employeeId', width: 55, stype: 'text', sortable: true, editable: true, formoptions: { rowpos: 1, colpos: 1 }, editrules: { integer: true} },
       { name: 'name', index: 'name', width: 90, stype: 'text', sortable: true, editable: true, editrules: { required: true }, formoptions: { rowpos: 2, colpos: 1} },
       { name: 'email', index: 'email', width: 100, stype: 'text', sortable: true, editable: true, editrules: { email: true, required: true }, formoptions: { rowpos: 2, colpos: 2} },
       { name: 'phone', index: 'phone', width: 80, align: "right", stype: 'text', sortable: true, editable: true, formoptions: { rowpos: 3, colpos: 1} },
       { name: 'pwd', index: 'pwd', width: 80, align: "right", stype: 'text', edittype: 'password', sortable: true, editable: true, formoptions: { rowpos: 3, colpos: 2} },
      { name: 'nationalId', index: 'nationalId', width: 80, align: "right", formatter: 'select',stype: 'select', editable: true, edittype: "select", editoptions: { value: getCountry() }, formoptions: { rowpos: 4, colpos: 1 }
                         },
     { name: 'dateOfBirth', index: 'dateOfBirth', width: 80, align: "right",
                              edittype: 'text', editable: true,
                              editoptions: { dataInit: function (el)
                               { $(el).datepicker({
                                      dateFormat: "dd/mm/yy",
                                      changeMonth: true,
                                      changeYear: true, }); } },
                              formoptions: { rowpos: 4, colpos: 2 }
                          }

                       ],
                        data: JSON.parse(data),
                        rowno: 10,
                        loadonce:true,
                        /* multiselect:true,*/
                        rowlist: [5, 10, 20],
                        pager: '#pager',
                        viewrecords: true,
                        gridview: true,
                        sortorder: 'asc',
                        toppager: true,
                        cloneToTop: true,
                        altrows: true,
                        autowidth: false,
                        hoverrows: true,
                        height:300,
                        rownumbers: true,
                        caption: "Employee Data"                           


                    });


                    $('#list').jqGrid('navGrid', '#pager',
                   {
                       edit: true,
                       add: true,
                       del: true,
                       search: false,
                       searchtext: "Search",
                       addtext: "Add",
                       edittext: "Edit",
                       deltext: "Delete",
                       cloneToTop: true

                         });
                        
/* to put search option in column toolbar*/
                    $("#list").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true });

/* move add ,edit ,delete button on top */
                    var grid = $("#list");
                    var topPagerDiv = $('#' + grid[0].id + '_toppager')[0
                    $("#" + grid[0].id + "_toppager_center", topPagerDiv).remove();                         $(".ui-paging-info", topPagerDiv).remove();

                    var bottomPagerDiv = $("div#pager")[0];
                    $("#add_" + grid[0].id, bottomPagerDiv).remove();
                    $("#edit_" + grid[0].id, bottomPagerDiv).remove();
                    $("#del_" + grid[0].id, bottomPagerDiv).remove();
                    $("#refresh_" + grid[0].id, bottomPagerDiv).remove();
                    // "#add_list"


                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    debugger;
                }
            });
        });


</script>

In the above grid national Names are in dropdown list ,so to fill the dropdown list dynamically use the below function 

  function getCountry() {
                var country;
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    data: "{}",
                    async: false,
                    url: "jqgridexample.aspx/getNational",
                    dataType: "json",
                    success: function (data) {

                        country = data.d;

                    },

                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        debugger;
                    }

                });
                return country;

            }

Now time to create web method.



        [WebMethod]
        public static string getEmployee()
        {
            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "fetchemployeeData";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = con;
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            con.Close();
            DataSet ds = new DataSet();
            da.Fill(ds);
            return Newtonsoft.Json.JsonConvert.SerializeObject(ds.Tables[0]);



        }

        [WebMethod]
        public static string getNational()
        { string returnvalue="";
            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "fetchNationality";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = con;
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            con.Close();
            DataSet ds = new DataSet();
            da.Fill(ds);
              returnvalue+=""+""+""+":All;";
                        for (var i = 0; i < ds.Tables[0].Rows.Count; i++) {

                            returnvalue += ds.Tables[0].Rows[i]["nationalId"].ToString().Trim() + ":" + ds.Tables[0].Rows[i]["natiionName"].ToString().Trim() + ";";
                        }
                        returnvalue = returnvalue.Remove(returnvalue.LastIndexOf(';'));
                      

                        return returnvalue;


        }



Don't forget to add newtonsoft ref to serialize your data in json format. To add newtonsoft dll follow the below steps
GOTO-Tools->Library Package manager->Package manager console
PM> Install-Package Newtonsoft.Json
Here are some properties of jqGrid:
data: set the data to bind the grid
colNames:   defines the columns Name as Header
colModel:   bind column value in rows
stype:      defines the search type (text or select)
sortable:   It can be sort or not
editable:   make it editable
edittypes:  types of control at the time of editing(textbox,select,checkbox etc)
editrules:  some validations and datatypes can be defined 
editoptions: to bind the dynamic data inside the controls
formoptions : defines form layout at the time of generating form for edit,add
edit: to show the edit button,
addto show the add button,
delto show the delete button,
searchto show the search button,
searchtext: search button text,
addtextAdd  button text,
edittextedit button text,
deltextdelete button text,
pager: div id to set the paging
multiselect: for select multiple rows
hoverows: shows tooltip on mouse hover
rownumbers :shows the row number

Any confusion contact to mkumar.soft@gmail.com.


Thursday, July 24, 2014

jquery datepicker with highlighted dates

Hi friends,
In my previous post I described some features of Jquery datepicker. Now In this post I am going to write how can we highlight the dates on the basis of condition in datepicker. 

So let's start:-

Suppose we are developing flight booking site and we need to show the seat Availability in calendar with some details in tool tip.

We are going to show Seat Availability status as 

1. Available
2.Not Available
3.No Flight(on the day)

So your final output will be like :-

Jquery datepicker with highlighted color:-


To get the above output lets start coding:

Add the jquery references on your page:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

Take div to bind the datepicker as 

<div class="ui-widget-header" style="width:100%; height:25px;">Seat Availability</div>
    <div style="width: 100%">
        <div id="dvBookingcalendar">  </div>/* div to bind the calendar*.
       
    </div>
/* for legend * /
    <br />
   Available <span style="background-color:Green;">&nbsp;&nbsp;&nbsp;&nbsp;</span>

  
   Not Available <span style="background-color:red;">&nbsp;&nbsp;&nbsp;&nbsp;</span>
  
   No Flight <span style="background-color:blue;">&nbsp;&nbsp;&nbsp;&nbsp;</span>

Now copy paste the below code into script block :
<<script type="text/javascript">
      var arraydate = [];/*dates which we are fetching from database */
      var arraycss = []; /*Css according to the status */
      var arrayStatus = []; /*Statuses of seat Availability */
      $(document).ready(function () {
          $.ajax({
              type: "POST",
              contentType: "application/json",
              data: "{'month':'" + 7 + "','year':'" + 2014 + "'}",
              url: "calendarColoring.aspx/returnFlightstatus",
              dataType: "json",
              success: function (data) {
                  for (var i = 0; i < data.d.length; i++) {
                  /*push the data in arrays so that at the time of binding dates we no need to call server methods*/
                      arraydate.push(data.d[i].date);
                      arraycss.push(data.d[i].css);
                      arrayStatus.push(data.d[i].status);

                  }

                  $("#dvBookingcalendar").datepicker({
                      dateFormat: 'dd/mm/yy',
                      changeMonth: true,
                      changeYear: true,
                      firstDay: 1,
                      showOtherMonths: false,
                      beforeShowDay: marksStatus/*This method will highlight the dates */
                   
                  });
              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                  debugger;
              }
          });

          var tooltips = "";
          function marksStatus(date) {
             /*function addZero will convert the dates in required format*/
             /*our dates are in yyyy-MM-dd format*/
              function addZero(no) {
                  if (no < 10) {
                      return "0" + no;
                  } else {
                      return no;
                  }
            }
var date_str = [addZero(date.getFullYear()), addZero(date.getMonth() + 1), addZero(date.getDate())].join('-');
  /*date_str :whatever calendar dates is going to print we store in the date_str*/

              for (var i = 0; i < arraydate.length; i++) {
                /* run loop on the dates which is in our array and match with date_str if matched then set the css else nothing */
                  if (date_str == arraydate[i].toString()) {
                      tooltips = "Status - " + arrayStatus[i].toString();
                      return [true, arraycss[i].toString(), tooltips];
                      break;
                  }
              }
             
              return [true, '', ''];
          }
      });  
    </script>

Now time to create our web method:
  [WebMethod]
  public static List<Members> returnFlightstatus(string month, string year)
        {

/* here I am taking only few dates dates can be filter out on the basis of month and year */
            List<Members> seatAvailability = new List<Members>();

  try
      {
seatAvailability.Add(new Members { status = "Available", date = "2014-07-23", css ="A"});
seatAvailability.Add(new Members { status = "Not Available",date = "2014-07-24",css =“NA" });
seatAvailability.Add(new Members { status = "Not Available",date = "2014-07-25",css="NA" });
seatAvailability.Add(new Members { status = "No Flight", date = "2014-07-26",css = "NOF" });
seatAvailability.Add(new Members { status = "Not Available",date = "2014-07-27",css ="NA" });
seatAvailability.Add(new Members { status = "Available", date = "2014-07-28", css = "A" });
seatAvailability.Add(new Members { status = "Available", date = "2014-07-29", css = "A" });
seatAvailability.Add(new Members { status = "Available", date = "2014-07-30", css = "A" });
seatAvailability.Add(new Members { status = "Available", date = "2014-07-31", css = "A" });
               
            }
            catch
            { 
            }

            return seatAvailability;
        }



Oh,Don't forget to create css as below:
<style>
        .ui-datepicker
        {
            width: 50%;
        }
        .A a
        {
     
        background-color: Green !important;
        background-image: none !important;
        color: #fff !important;
        font-weight: bold !important;
   
         }
             
       .NA a
        {
     
        background-color: Red !important;
        background-image: none !important;
        color: #fff !important;
        font-weight: bold !important;
  
}
.NOF a
        {
     
        background-color: Blue !important;
        background-image: none !important;
        color: #fff !important;
        font-weight: bold !important;
  
   
              }
       
   That's it ,Now our calendar is ready to show Seat Availability .


Happy coding..








Tuesday, July 22, 2014

jquery datepicker

Jquery datepicker is a powerful calendar ,that can be used in place of ajax calendar or others.Here are some useful features of jquery datepicker.

How to add jquery datepicker in textbox:

  $(document).ready(function () {
        $('#textboxDate').datepicker({
                            dateFormat: "dd/mm/yy",
                           changeMonth: true,
                           changeYear: true,
                           showOtherMonths: false,
                           onChangeMonthYear: callyourfunction,
                           beforeShowDay:myfunction,
showButtonPanel: true,
numberOfMonths: 2,
                           onSelect: function (dateText, inst) {

                             myfunction(dateText);
                     
                             }
                   });        
    });

  • To set the dateformat in datepicker use:   dateFormat: "dd/mm/yy",
1. mm/dd/yy (default)
2. yy-mm-dd"(ISO 8601 - yy-mm-dd)
3. d M, y"(Short - d M, y)
4. d MM, y"(Medium - d MM, y)
5. DD, d MM, yy"(Full - DD, d MM, yy)
6. "&apos;day&apos; d &apos;of&apos; MM &apos;in the year&apos; yy"(With text - 'day' d 'of' MM 'in the year' yy)
  • To enable the selection of month,year use: changeMonth: true, changeYear: true

  • To do some action before day print in calendar call event  beforeShowDay,in your function you will be able to get current date month year one by one -1,2,3 etc
          e.g  beforeShowDay:myfunction

          function   myfunction(date)
                 {
                    alert (date);
                  }

  • on selection of date  call an event  onSelect  to check some date validation,call your javascript function like 
        function myFunction(date)
            {
                  alert(date)/* selected date by users/*

                }
  • on change other month or year if required some action use :onChangeMonthYear
  • showButtonPanel: true, to show the button in the bottom of calendar

  • To Dislpay multiple months use numberOfMonths: 3(number of month),

  • $("#txtCalender").datepicker("refresh") : to Refresh/rebinding the calender
Happy coding


Thursday, July 17, 2014

Autocomplete Textbox in Jquery with ID (hidden)

Hello friends ,
Today I am going to post Auto complete textbox using Jquery with hidden Id.
When we develop Autocomplete text box then we need to show the Name and Id should be hidden, at the time of saving data we need ID.
Same scenario we are going to cover in this post, hope it will be helpful.

Task: Create a autocomplete textbox with employee Name and Id (Id should be hidden)
 
Add jquery reference on the page :

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
we need above three references.

Now take textbox and hidden field 
  <input type="text" id="txtEmployee" />
 <input type="hidden" id="hdnEmpId" />
/*we can take aspx control instead of html control it's up to u*/

Copy & paste the below code inside the script block:
  #("#txtEmployee").autocomplete({
                 source: function (request, response) {
                      #("#hdnEmpId").val("0");/* set the intial id =0  */                 
                      #ajax({
                         url: "testJquery.aspx/getEmployeList",/*web method path*/
                         data: "{'prefixText': '" + request.term + "'}",
                         dataType: "json",
                         type: "POST",
                         contentType: "application/json; charset=utf-8",
                         dataFilter: function (data) { return data; },
                         success: function (data) {
                             response($.map(data.d, function (item) {
                                 return { label: item.ename,/*property Names */
                                          value: item.ename
                                          id: item.eid 
                                        }
                             }))
                         },
                         error: function (XMLHttpRequest, textStatus, errorThrown) {
                             var err = eval("(" + XMLHttpRequest.responseText + ")");
                             alert(err.Message);
                         }
                     });
                 },
                 minLength: 1,//define the length of letter
                 noCache: false,
                 select: function (event, ui) {
                      #("#txtEmployee").val(ui.item.value);/* set the value on selection*/
                      #("#hdnEmpId").val(ui.item.id);/* set the Id on selection*/
                    
                 }

             });

Now next step to create the web method 
Note :instead of web method we can use Handler,web service ,xml as per your requirement .


[WebMethod]
    public static List<emp> getEmployeList(string prefixText)
    { 
       /* I assume that u select data on the basis of parameter either from database or list */
        

         //You can get data from data base and add in list
        List<emp> employee= new List<emp>();
        employee.Add(new Country { eid  = "1", ename = "Manoj" });
        employee.Add(new Country { eid  = "2", ename = "Singh" });
        employee.Add(new Country { eid  = "3", ename = "Suraj" });
        employee.Add(new Country { eid  = "4", ename = "Vishal" });
        employee.Add(new Country { eid  = "5", ename = "Deepak" });
        employee.Add(new Country { eid  = "6", ename = "Prashant" });
        employee.Add(new Country { eid  = "7", ename = "Pankaj" });
        return employee;

    }

 Now our autocomplete textbox is ready to use.


Happy coding.

label value in Jquery

Label In Jquery
Many times we use get get the value of label :- $("#lblId").val();
But It doesn't work .
So best Solution is 
To Set the value in Label :- $("#lblId").innerHtml("your string");
To get the value use : $("#lblId").text();

Wednesday, July 16, 2014

Selectors in Jquery:

Jquery provides some selector to make easy developer's works:

Below are those selectors:

1. #(ID selector) is used when need to select any control with Id
         e.g  <div id="dvemplist"></div>

               $("#dvemplist").html('your string');

2. element selector is used to select element
    e.g : $("p").hide(); can be select all P element of the page.
3. Class selector (.) is used to select all the controls with class name
        $(".your css name").show();
4. * to select all the  element
     $("*")

Note : Always try to use Id selector because it gives better performance than others


Except these  bellows are very useful:

$("*") Selects all elements
$(this) Selects the current HTML element
$("p.intro") Selects all <p> elements with class="intro"
$("p:first") Selects the first <p> element
$("ul li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child") Selects the first <li> element of every <ul>
$("[href]") Selects all elements with an href attribute
$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank"
$(":button") Selects all <button> elements and <input> elements of type="button"
$("tr:even") Selects all even <tr> elements
$("tr:odd")

(source from w3c)



Selects all odd <tr> elements





    

Convert Html to Pdf in azure function and save in blob container

 In this post  I am going to create an azure function ( httpTrigger ) and send html content  which will be converted into PDF and save in bl...