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);
}
}

4 comments:

  1. Could you please provide me your method named
    "ConvertDataTabletoString",
    "ConvertStringArrayToString",
    "ConvertStringArrayToStringModel"



    i have created my own method but its not working.
    bellow is my method.
    public static string ConvertDataTabletoString(this DataTable dt)
    {
    StringBuilder stringBuilder = new StringBuilder();
    dt.Rows.Cast().ToList().ForEach(dataRow =>
    {
    dt.Columns.Cast().ToList().ForEach(column =>
    {
    stringBuilder.AppendFormat("{0}:{1} ", column.ColumnName, dataRow[column]);
    });
    stringBuilder.Append(Environment.NewLine);
    });
    return stringBuilder.ToString();
    }

    public static string ConvertStringArrayToString(string[] array)
    {
    StringBuilder builder = new StringBuilder();
    foreach (string value in array)
    {
    builder.Append(value);
    builder.Append(',');
    }
    return builder.ToString();
    }
    public static string ConvertStringArrayToStringModel(string[] array)
    {
    //
    // Concatenate all the elements into a StringBuilder.
    //
    StringBuilder builder = new StringBuilder();
    foreach (string value in array)
    {
    builder.Append(value);
    builder.Append(',');
    }
    return builder.ToString();
    }

    ReplyDelete
    Replies
    1. pls find below

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

      static string ConvertStringArrayToString(string[] array)
      {
      string result = string.Join("\",\"", array);
      result = "[\"" + result + "\"]";
      return result;
      }

      public string ConvertStringArrayToStringModel(string[] array)
      {
      StringBuilder builder = new StringBuilder();
      builder.Append("[");
      foreach (string value in array)
      {
      builder.Append("{ \"name\":\"");
      builder.Append(value);
      builder.Append("\",\"index\":\"");
      builder.Append(value);
      builder.Append("\"},");
      }
      builder = builder.Remove(builder.Length - 1,1);
      builder.Append("]");
      return builder.ToString();
      }

      Delete
  2. I have used the same method.that is loading only Column Headers but not records. can you please help me.

    ReplyDelete
    Replies
    1. So Sorry to reply you late, I hope you must have solved your problem but if not can you pls show me your code?

      Delete