Jqgrid与mvc4

时间:2015-08-01 06:56:51

标签: jqgrid

我想在运行时创建动态Jqgrid。我已经制定了两种方法

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


        lst = new List<UserModel>();
        lst = uservice.GetAllUsers();

        var listOfStrings = new List<string>();



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


    }

getcolumdetail用于获取列名,获取数据用于获取数据。

div class="row">
    <div id="content" style="margin-left:15px !important;">
        <table id="datacopyProject"></table>
        <div id="datacopy_pagerProject"></div>
        @*<table id="datacopyfilter"></table>
            <div id="datacopy_pagerfilter"></div>*@
    </div>
</div>
<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;
    }

我在jQgrid中获取列值但没有获取行。

1 个答案:

答案 0 :(得分:0)

您可以使用此post中说明的解决方案,并从控制器返回一个ViewBag并加入这些变量:

var jsonGrid = jQuery.parseJSON('@Html.Raw(ViewBag.YourGridVariableInJson)');