0
Answer

How Can I Create Jqgrid In Mvc Dynamically

Sujit Jha

Sujit Jha

9y
1k
1
I have created two method like
public ActionResult getdata(List<UserModel> lst )         {             UserModel usermodel = new UserModel();             UserService uservice = new UserService();             //return View(db.VideoModels.OrderByDescending(v => v.VideoId).ToPagedList(page, 3));             string[] columnNames = (string[])TempData["columnname"];               lst = new List<UserModel>();             lst = uservice.GetAllUsers();                     JavaScriptSerializer serializer = new JavaScriptSerializer();             List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();             Dictionary<string, object> row;             foreach (var dr in lst)             {                 row = new Dictionary<string, object>();                      rows.Add(row);             }             return Json(serializer.Serialize(lst), JsonRequestBehavior.AllowGet);         }                            public ActionResult GetColumnDetails( List<UserModel> lst)         {             UserModel usermodel = new UserModel();             UserService uservice = new UserService();             //return View(db.VideoModels.OrderByDescending(v => v.VideoId).ToPagedList(page, 3));                                      lst = new List<UserModel>();             lst = uservice.GetAllUsers();             //   id =  (int)Session["id"] ;             //  dt = GetTableDetails(id);                             //string[] columnNames = lst.             //                     Select(x => x.)             //                     .ToArray();             //string[] columnNames = (from ss in lst.GetType().GetProperties() select ss.Name).ToArray();             //string colNames = string.Empty;             var listOfStrings = new List<string>();               // do stuff...              string[] colNames = listOfStrings.ToArray();             string[] columnNames = (from t in typeof(PrTblUsers).GetProperties() select t.Name).ToArray();                          JavaScriptSerializer serializer = new JavaScriptSerializer();             return Json(serializer.Serialize(colNames= columnNames), JsonRequestBehavior.AllowGet);            }t);            }
 getGetColumnDetails is for getting the column header and getdata is for getiing records.
In the view i use like this
div class="row">

@*
*@

<script type="text/javascript" id="getdata">

$(document).ready(function () {
var item = [];
//creating the dyanamic colmodel
$("#datacopyProject").jqGrid('GridUnload');

$.ajax(
{
type: "POST",
url: '/Test/GetColumnDetails',
//data: { tid: data },
dataType: "json",
success: function (result) {
var colModels = BuildColumnModel(JSON.parse(result));
//console.log(JSON.stringify(result));
//var obj = jQuery.parseJSON(result);

//var columnData = result.mypage,



item= getData();

//alert(item);
jQuery("#datacopyProject").jqGrid({

colNames: item,
colModel: colModels,
autowidth:true,
caption: "User List",
pager: jQuery('#datacopy_pagerProject'),
rowNum: 3,
viewrecords: true,
rowList: [5, 10, 20, 50],

viewrecords: true,
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return $("#datacopyProject").jqGrid('getGridParam', 'page'); },
total: function (obj) { return Math.ceil(obj.length / $("#datacopyProject").jqGrid('getGridParam', 'rowNum')); },
records: function (obj) { return obj.length; }
},
gridComplete: function () {




},
loadComplete: function (data) { }

})
},
loadonce:true,
error: function (x, e) {
alert(x.readyState + " " + x.status + " " + e.msg);
}

});

//setTimeout(function () { $("#datacopyProject").jqGrid('setGridParam', { datatype: 'json' }); }, 500);

//binding the data to dyanamic colmodel
function getData()
{

$.ajax({

url: '/Test/getdata',
type: "POST",
datatype: "json",
//data: { userid: data },

async: false,
success: function (response) {

var resultData = JSON.parse(response);
//var data = resultData.slice(1, resultData.length - 1);
//var json = JSON.stringify(data);
//console.log(resultData);
////var resultData = JSON.parse(response);

for (var i = 0; i <= resultData.length; i++)
item = $("#datacopyProject").jqGrid('addRowData', i + 1, datacopyProject[i]);

//$(resultData).each(function (e) {
// $("#datacopyProject").addRowData(e, this);

//});
}
});


}
});
function BuildColumnModel(result) {
debugger;
// var uFields = result.split(',');
var uFields = result;

var columns = [];
for (var i = 0; i < uFields.length ; i++) {
if (uFields[i].indexOf('Id') > -1) {
columns.push({ name: uFields[i], index: uFields[i], key: true });
//columns.push({ 'name': name, 'index': name, key: true});

}
// else if (uFields[i].indexOf('Name') > -1) {
else if (uFields[i].length > -1) {
columns.push({ name: uFields[i], index: uFields[i] })
// columns.push({ 'name': name, 'index': name });
}
//else if (uFields[i].length > -1) {
// columns.push({ name: uFields[i], index: uFields[i]})
// //columns.push({ 'name': name, 'index': name, key: true });
//}
}
return columns;
}
When i run the application column shows in jqgrid but rows are not showing.Anyone please help.Urgent otherwise i have..Also it's inbult functionality like universal search search by column not workingThanks