Monday 9 December 2013

Change TabIndex on Hide/Show Elements - JQuery

Hello Friends,

This scenario comes sometimes. when we need conditional tabbing with selecting some option will hide some elements or show some elements so in that case we need to change TabIndex dynamically like the following image.
When I select Cat2 in Dropdownlist all textboxes are visiable.


Now when I select Cat3 Textbox 4,6 and 9 are invisiable and Textbox7 comes in place of Textbox4. so after Textbox3 Cursor should move to Textbox7 and then Textbox5. so I need to change Tabindex of Textbox7 to 4.

for that I am using JQuery's nextuntil() function. so I can replace the following elements of Hidden Element to new TabIndex into the same div.

<script type="text/javascript">
    function changeDrp()
    {
        var value = $("#Select").val();
        if (value == "Cat1")
        {
            ResetAll();
            $("#Test8").hide();
            $("#Test5").hide();
            $("#Test6").hide();
            $("#Test1").hide();
            NewAssignTab();
        }
        else if (value == "Cat2")
        {          
            $("*[ dataitem ='Textbox']").show();
            ResetAll();
        }
        else if (value == "Cat3")
        {
            ResetAll();
            $("#Test6").hide();
            $("#Test9").hide();
            $("#Test4").hide();
            NewAssignTab();
        }
    }

    function NewAssignTab()
    {      
        jQuery("*[ dataitem ='Textbox']").each(function ()
        {        
            if (this.style.display == "none")
            {
                var pre,next;
                next = this.tabIndex;
                $("#" + this.id).nextUntil("#class:last").each(function ()
                {
                    pre = this.tabIndex;
                    this.tabIndex = next;
                    next = pre;                  
                });
            }
        });
    }

    function ResetAll()
    {
        jQuery("*[ dataitem ='Textbox']").each(function ()
        {          
            this.tabIndex = $("#" + this.id).attr("originaltab");
        });
    }
</script>

<div id="main">
     @{
        List<SelectListItem> listItems = new List<SelectListItem>();
        listItems.Add(new SelectListItem
        {
            Text = "Cat1",
            Value = "Cat1"
        });
        listItems.Add(new SelectListItem
        {
            Text = "Cat2",
            Value = "Cat2",
            Selected = true
        });
        listItems.Add(new SelectListItem
        {
            Text = "Cat3",
            Value = "Cat3"
        });
    }

    @Html.DropDownList("Select", listItems, new { onchange="changeDrp();" })<br />

    <div id="dv1" style="width: 33%; float: left;">
        <input id="Test1" type="Text" value="1" tabindex="1" dataitem ="Textbox" originaltab ="1" />
        <input id="Test4" type="Text" value="4" tabindex="4" dataitem ="Textbox" originaltab ="4" />
        <input id="Test7" type="Text" value="7" tabindex="7" dataitem ="Textbox" originaltab ="7" class="last" />
    </div>
    <div id="dv2" style="width: 33%; float: left;">
        <input id="Test2" type="Text" value="2" tabindex="2" dataitem ="Textbox" originaltab ="2" />
        <input id="Test5" type="Text" value="5" tabindex="5" dataitem ="Textbox" originaltab ="5" />
        <input id="Test8" type="Text" value="8" tabindex="8" dataitem ="Textbox" originaltab ="8" class="last" />
    </div>
    <div id="dv3" style="width: 33%; float: left;">
        <input id="Test3" type="Text" value="3" tabindex="3" dataitem ="Textbox" originaltab ="3" />
        <input id="Test6" type="Text" value="6" tabindex="6" dataitem ="Textbox" originaltab ="6" />
        <input id="Test9" type="Text" value="9" tabindex="9" dataitem ="Textbox" originaltab ="9" class="last" />
    </div>
</div>

Here in Last Element of the Div I had added class="last" attribute. so JQuery function will stop assigning new Index to the Elements.

Friday 6 December 2013

Bind JQgrid with Dynamic Columns in MVC

Hello Friends,
In this blog I am creating JQgrid with dynamic columns.

In this example Every time I am giving Connection String and Query dynamically to JQgrid to bind the data.
Code is as follows

<div class="editor-label">
@Html.Label("ConnectionString")
</div>
<div class="editor-field">
@Html.TextBox("ConnectionString")
</div>

<div class="editor-label">
@Html.Label("Query")
</div>
<div class="editor-field">
@Html.TextArea("Query")
</div>

<button type="submit" id="btnGetData" name="Command" value="GetData" onclick="return GetData();" class="btn">Get Data</button>

<div id="dvJqGrid" class="dvjq">
<table id="grid" class="scroll"></table>
<div id="pager" class="scroll" style="text-align: center;"></div>
</div>

<script type="text/javascript">  
function GetData() {
setTimeout(function () { $('#dvLoader').show();},1);
var ConnectionString = document.getElementById("ConnectionString").value;
var Query = document.getElementById("Query").value;

$("#dvJqGrid").empty();
$("#dvJqGrid").append($("<table>").attr("id", "grid"));
$("#dvJqGrid").append($("<div>").attr("id", "pager"));

$.ajax(
{
type: "POST",
url: "/QueryPad/JQGridGetDataWithColumn",
data: { "ConnectionString": ConnectionString, "Query": Query },
dataType: "json",
success: function (result) {
$("#Result").val(result.Msg);
colD = result.colData;
colN = JSON.parse(result.colNames);
colM = JSON.parse(result.colModel);

var SQL = ConnectionString;
var Oracle = ConnectionString;
jQuery("#grid").jqGrid({
jsonReader: {
cell: "",
id: "0"
},
url: '/QueryPad/JQGridGetData',
postData: { ConnectionString: ConnectionString, Query: Query, QueryType: QType },
datatype: 'json',
mtype: 'POST',
datastr: colD,
colNames: colN,
colModel: colM,
pager: jQuery('#pager'),
rowNum: 5,
page: 1,
rowList: [5, 10, 20, 50],
viewrecords: true,
loadonce: false
});
$('#dvLoader').hide();
},
error: function (x, e) {
$('#dvLoader').hide();              
}
});
setTimeout(function () { $('#dvLoader').hide(); }, 1000);
return false;
}
</script>

public string JQGridGetData(string sidx, string sord, int page, int rows,string ConnectionString,string Query)
{          
SqlConnection con = new SqlConnection(ConnectionString);
try
{
con.Open();
SqlTransaction sqlTran = con.BeginTransaction();
try
{
SqlCommand cmd1 = new SqlCommand(Query, con);
cmd1.Transaction = sqlTran;
DataTable dt = new DataTable();
SqlDataReader dr = cmd1.ExecuteReader();
dt.Load(dr);
if (dt.Rows.Count > 0)
{
string StringData = ConvertDataTabletoString(dt);
sqlTran.Commit();
con.Close();
return StringData;
}
else
{
Exception exx = new Exception();
throw exx;
}
}
catch (Exception ex)
{
sqlTran.Rollback();
con.Close();
ViewBag.Result = ex.Message;
return "";
}
}
catch (Exception ex)
{
con.Close();
return "";
}

}

public JsonResult JQGridGetDataWithColumn(string ConnectionString, string Query)
{  
SqlConnection con = new SqlConnection(ConnectionString);
try
{
con.Open();
SqlTransaction sqlTran = con.BeginTransaction();
try
{
SqlCommand cmd1 = new SqlCommand(Query, con);
cmd1.Transaction = sqlTran;
DataTable dt = new DataTable();
SqlDataReader dr = cmd1.ExecuteReader();
dt.Load(dr);
if (dt.Rows.Count > 0)
{
sqlTran.Commit();
con.Close();
string StringData = ConvertDataTabletoString(dt);
string[] columns = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
string columnNames = ConvertStringArrayToString(columns);
string columnModel = ConvertStringArrayToStringModel(columns);
return Json(new { colData = StringData, colNames = columnNames, colModel = columnModel, Msg = "Data Successfully Loaded" }, JsonRequestBehavior.AllowGet);
}
else
{
Exception exx = new Exception();
throw exx;
}
}
catch (Exception ex)
{
sqlTran.Rollback();
con.Close();
ViewBag.Result = ex.Message;
return Json(new {Msg = ex.Message },JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
con.Close();
return Json(new { Msg = ex.Message }, JsonRequestBehavior.AllowGet);
}
}

Bind JQgrid in MVC

Hello Friends,
Here is simple example how to bind JQgrid in MVC.

<table id="grid" class="scroll"></table>
 <div id="pager" class="scroll" style="text-align: center;"></div>

 $(document).ready(function () {

        $("#grid").jqGrid({
            url: "/QueryPad/GetData",
            datatype: "json",
            mtype: "GET",
            colNames: ["Product ID", "Name", "Price"],
            colModel: [
                        { name: "ProductID", index: "ProductID" },
                        { name: "Name", index: "Name" },
                        { name: "Price", index: "Price" }
            ],
            rowNum: 1,
            rowList: [20, 50, 100],
            pager: "#pager-json",
            sortname: "ProductID",
            sortorder: "ASC",
            viewrecords: true,
            caption: "Get Data"
        });
});

public string GetData()
{
string ConnectionString = ""; // Put your connection string here
string Query = "Select * from Product";
SqlConnection con = new SqlConnection(ConnectionString);
try
{
SqlCommand cmd1 = new SqlCommand(Query, con);
DataTable dt = new DataTable();
SqlDataReader dr = cmd1.ExecuteReader();
dt.Load(dr);
string StringData = ConvertDataTabletoString(dt);
con.Close();
return StringData;
}
catch (Exception ex)
{
con.Close();
ViewBag.Result = ex.Message;
return "";
}
}

public string ConvertDataTabletoString(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);              
}

Open Dialogbox in jQuery UI MVC

Hello Friends,
Open a Dialogbox is required so manytimes in our porject. so use the following code for this.

<link href="~/Content/themes/base/jquery.ui.dialog.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery-ui-1.8.20.min.js"></script>

<button id="show-dialog" tabindex="3">Click Open Dialogbox</button>          
<div id="dialog" title="Dialogbox Title" >
   <p>This is a simple Dialogbox body</p>
</div>  

@section scripts {
    <script type="text/javascript">
        $('#dialog').dialog({
            autoOpen: false,
            width: 600,
            buttons: {
                "Ok": function () { $(this).dialog("close"); },
                "Cancel": function () { $(this).dialog("close"); }
            }
        });
        $("#show-dialog").button().click(function () {
            $('#dialog').dialog('open');
            $('#dialog').attr('tabIndex', -1).css('outline', 0).focus().keydown(function (ev)
            {
                if (ev.keyCode && ev.keyCode === jQuery.ui.keyCode.ENTER)
                {
                    $('#dialog').dialog('close');
                }
            });
            return false;
        });
     
    </script>
}