Having trouble loading JSON data in jqGrid

Why is the JSON data not loading in jqGrid?

I am using ASP.net with C# along with JQGrid using JavaScript and AJAX.

Below is my code:

  public string Alarm_Main()
{
    SqlConnection con = new SqlConnection(ConnString);
    DataTable dt = new DataTable();
    con.Open();
    string query = "select * from MST_ALARM_TYPE";
    SqlDataAdapter da = new SqlDataAdapter(query, con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();
    return JsonConvert.SerializeObject(ds.Tables[0]);
}

In the file: DataService.aspx; here is the given code:

<script>
    $(function () {
        $("#list").jqGrid({
            url: 'DataService.asmx/Alarm_Main',
            datatype: 'json',
            mtype: 'POST',
            serializeGridData: function (postData) {
                alert(JSON.stringify(postData));
                return JSON.stringify(postData);
            },
            ajaxGridOptions: { contentType: "application/json;charset=utf-8;" },
            loadonce: true,
            jsonReader: {
                page: function (obj) { return 1; },
                total: function (obj) { return 1; },
                records: function (obj) { return obj.d.length; },
                root: function (obj) { return obj.d; },
                repeatitems: false,
                id: "0"
            },
            colNames: ['', '알람코드', '등록날짜', '알람명', '등록자', ''],
            colModel: [
                { name: 'myradio', width: 30, search: false, fixed: true, align: 'center', resizable: false, sortable: false, frozen: true, formatter: function (cellValue, option) { return '<input type="radio" name="radio_' + option.gid + '"/>'; }, frozen: true },
                { name: 'alarm_type_code', index: 'alarm_type_code', align: 'center', width: 200, frozen: true, sorttype: 'number' },
                { name: 'regist_date', index: 'regist_date', width: 200, editable: true, frozen: true, align: 'center', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "Y-m-d", newformat: "Y-m-d" } },
                { name: 'alarm_type_name', index: 'alarm_type_name', width: 200, frozen: true },
                { name: 'regist_name', index: 'regist_name', width: 200, frozen: true },
                { name: 'myac', width: 50, search: false, fixed: true, sortable: false, resizable: false, fommatter: 'action', formatoptions: {keys:true}}
            ],
            rowNum: 10,
            rowList: [5, 10, 20, 50],
            width: '100%',
            pager: '#pager',
            gridview: true,
            rownumbers: false,
            sortable: true,
            multiselect: true,
            scrollOffset: 0,
            cellEdit: true,
            sortorder: 'desc',
            caption: '그리드 제목',
            height: '100%',
            shrinkToFit: true,
            loadonce: true
        });
        jQuery("#list").jqGrid('setFrozenColumns');
        jQuery("#list").trigger('reloadGrid');
        jQuery("#list").jqGrid('navGrid', '#pager', { excel: true, add: true, edit: true, view: true, del: true, search: true, refresh: true },
            { closeAfterAdd: true, reloadAfterSubmit: false, closeOnEscape: true },
            { closeAfterAdd: true, reloadAfterSubmit: false, closeOnEscape: true },
            { reloadAfterSubmit: false, closeOnEscape: true },
            { multipleSearch: true, multipleGroup: true, showQuery: true, closeOnEscape: true, onSearch: function () { } }, { closeOnEscape: true });
        jQuery("#list").jqGrid('bindKeys', { "onEnter": function (rowid) { alert("You enter a row with id:" + rowid) } });
        jQuery("#list").jqGrid('navButtonAdd', '#pager', { caption: "Excel", onClickButton: function () { jquery("#list").jqGrid('excelExport', { url: 'D:\\' }); } });
        jQuery("#list").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: "cn" });
    });
</script>

I cannot see anything on my screen.

What could be the issue?

Answer №1

Here is an example of how to utilize ado.net with jqgrid, which I trust will be beneficial for you.

Controller"

 public ActionResult GetCustomer(int rows, string sidx, string sord, int page)
        {
            List<Customer> _customerList = new List<Customer>();

            DataTable dt = new DataTable();
            string strConString = @"Data Source=gen5win10;Initial Catalog=AsifDb;Integrated Security=True";

            using (SqlConnection con = new SqlConnection(strConString))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("Select * from Customer", con);

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.SelectCommand = cmd;
                DataSet ds = new DataSet();
                da.Fill(ds);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    Customer cobj = new Customer();
                    cobj.CustomerId = Convert.ToInt32(ds.Tables[0].Rows[i]["CustomerId"].ToString());
                    cobj.ID = Convert.ToInt32(ds.Tables[0].Rows[i]["CustomerId"].ToString());
                    cobj.Name = ds.Tables[0].Rows[i]["Name"].ToString();
                    cobj.Phone = ds.Tables[0].Rows[i]["Phone"].ToString();
                    cobj.Address = ds.Tables[0].Rows[i]["Address"].ToString();
                    cobj.Date = Convert.ToDateTime(ds.Tables[0].Rows[i]["Date"].ToString());

                    _customerList.Add(cobj);
                }

            }

                int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;

            var Results = _customerList.Select(
                    a => new
                    {
                        a.ID,
                        a.Name,
                        a.Phone,
                        a.Address,
                        a.Date,
                    });

            int totalRecords = Results.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            if (sord.ToUpper() == "DESC")
            {
                Results = Results.OrderByDescending(s => s.ID);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            else
            {
                Results = Results.OrderBy(s => s.ID);
                Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = Results
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);

} 

HTML:

<link href="~/Scripts/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.css" rel="stylesheet" />
<link href="~/Scripts/Guriddo_jqGrid_JS_5.2.0/css/ui.jqgrid.css" rel="stylesheet" />

<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/jquery-1.11.0.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1/jquery-ui-1.12.1/jquery-ui.js"></script>

<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/Guriddo_jqGrid_JS_5.2.0/js/jquery.jqGrid.min.js"></script>

<h2>Customers</h2>

<br>

<script type="text/javascript">
    $(document).ready(function () {

        $('#sample').jqGrid({
            datatype: 'Json',
            url: '/Customer/GetCustomer',
            type: 'POST',
            colNames: ['ID', 'Name', 'Phone', 'Address', 'Date'],
            colModel:
            [
                {key:true , name: 'ID', index: 'ID', editable: false },
                {name: 'Name', index: 'Name', editable: true ,editoptions: {maxlength: 15 },editrules:{ required: true,  }, },
                {  name: 'Phone', index: 'Phone', editable: true,  editoptions: {   maxlength: 15, },editrules: { required: true, },},
                {name: 'Address', index: 'Address', editable: true, editoptions: { maxlength: 30,}, editrules: {required: true,},},
                { name: 'Date', index: 'Date', editable: false, formatter: "date" },
            ],
            pager: jQuery('#pager'),
            jsonReader: {
                root: "rows",
                page: "page",
                total: "total",
                records: "record",
                repeatitems: false,
                Id: "0"
            },
            caption: 'Sample JqGrid Table',
            viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 30, 40],
            height: '100%',
           // multiselect: true

        }).navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true },
             {
                 // edit options
                 url: '/Customer/EditCustomer',
                 closeOnEscape: true,
                 closeAfterEdit: true,
                 recreateForm: true,
                 afterComplete: function (response)
                 {
                     if (response.responseText) {
                         alert(response.responseText);
                     }
                 }

             },

           {
               //add
               url: '/Customer/AddCustomer',
               closeOnEscape: true,
               closeAfterAdd: true,
               afterComplete: function (response) {
                   if (response.responseText) {
                       alert(response.responseText);
                   }
               }
           },
             { //Options for Delete
                 url:'/Customer/DeleteCustomer',
                 closeOnEscape: true,
                 closeAfterAdd: true,
                 afterComplete: function (response)
                 {
                     if (response.responseText) {
                         alert(response.responseText);
                     }
                 }

             }
             );

    });


</script>



<table id="sample"></table>
<div id="pager"> </div> 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging Ajax and jQuery to create a POST request for adding a new record to a MySQL table within a Node.js server

My form is designed to collect user information like name, age, and more. The aim is to submit this data from the client side, inserting it into a MySQL table row. However, I'm facing difficulties in getting the data to successfully insert. Below are ...

I am encountering an issue with Three.js version r69

I encountered an issue with line geometry.vertices.push(new THREE.Vertex(vector)); In the earlier version of Three.js, r36, this line was functioning. var vector = new THREE.Vector3(-300 + x/4, 240 - y, 0); geometry.vertices.push(new THREE.Vertex(ve ...

Create an array of various tags using the ngRepeat directive to iterate through a loop

I'm familiar with both ngRepeat and forEach, but what I really need is a combination of the two. Let me explain: In my $scope, I have a list of columns. I can display them using: <th ng-repeat="col in columns">{{ col.label }}</th> This ...

Identifying the presence of vertical scrolling

Is there a way to achieve the same functionality in JavaScript without using jQuery? I am looking to detect the visibility of the scrollbar. $(document).ready(function() { // Check if body height is higher than window height :) if ($("body").heigh ...

The request to http://localhost:7500/api/users/posts has resulted in a 400 error response indicating a Bad

Currently, I am in the process of saving data to a MongoDB database using Axios. I have set up a form for users to fill out and upon clicking the save button, the data should be stored. This is how my code looks: import auction1 from '../../Imag ...

I am wondering about the proper method for deleting multiple records simultaneously in Ember Data

My current challenge involves managing a list of record IDs, such as [1, 20, 20]. The process of individually querying and deleting each item is proving to be quite inefficient. store.findRecord('post', 1).then(function(post) { post.deleteRec ...

Transforming a string array into a class list within the Unity3d environment

I'm currently facing an issue with converting a WWW string array into a class list. My goal is to instantiate a prefab that contains multiple text elements. Below is the main class structure: public class VehicleIndex : MonoBehaviour { public st ...

Error with Ant Design Autocomplete functionality when searching for a number

I am currently using ant design to develop a more advanced autocomplete component that will display data from multiple columns. In this particular scenario, I have two columns named tax_id and legal_name that users can search by. Everything works smoothly ...

Can you explain the distinction between System.Diagnostics.Trace, System.Diagnostics.Debug, and System.Console?

I'm curious about the default behaviors of System.Diagnostics.Trace and System.Diagnostics.Debug in contrast to System.Console. Are these behaviors configurable? It seems there is some confusion online regarding this topic, but I believe there are spe ...

Error message stating that the callback function was not triggered by the injected JSONP script in Angular

Currently, I am running an application on localhost://3000 using npm server. Here is the content of my services file: import {Injectable} from "@angular/core"; import {Jsonp} from "@angular/http"; import 'rxjs/add/operator/map'; @Injectable() ...

What is the best way to initiate animation on a child element once the parent element has reached 75% completion of its animation

Is there a way to use JavaScript to determine when an animation is 75% complete? I have many nested HTML elements that need to be animated with an animation delay property, where the nested animation should start when the parent element is 75% complete. I ...

Disable the click functionality while preserving the hover feature

Due to my previous question being incorrectly marked as a duplicate, even though it wasn't, and no one is rectifying the mistake, I am re-posting my inquiry. I am dealing with an <a> element that has a default onClick function. This <a> a ...

Triggering a click event from a parent directive in Angular

I am in the process of developing a directive to display variances in text. To achieve this, I require a couple of buttons that have been separated into directives. A simplified illustration is as follows: .directive('differenceViewer', function ...

Generate a form using code that has the trigger turned off by default

Summary: Looking for a solution to avoid the automatic disabling of a programmatically created trigger in a form. function autoTrigger(e) { var result = {}; var responses = e.response.getItemResponses(); for (var i = 0; i < responses.length; i++) ...

Combine the values within the labels contained in the list view

Is there a way to calculate and display the total of all values in the labels generated in the (List View)? If possible, I would also like to show the sum in another label. <asp:Label ID="lbl_Plural" runat="server" Text="0& ...

What are the best ways to identify memory leaks in a react native application?

In my react native Android learning management system app, I have utilized AsyncStorage for simpler state management instead of using redux. However, a major issue I am currently facing is that the app slows down significantly when used continuously to per ...

What is the method for getting my character to jump in Phaser 3?

I'm a beginner in Phaser 3 and I'm facing an issue with my character's jumping mechanic. Here is the code snippet I'm currently using: create() { this.player = this.physics.add.sprite(50, 380, 'idle'); this.player.set ...

Serialization of data on a Custom DataSourceControl allows for the efficient storage

I am currently developing a custom DataSourceControl that will mimic the Select functionality of an ordinary ObjectDataSource, complete with properties like TypeName and SelectMethod. In my implementation, data retrieved from the TypeName class will be st ...

Discover the route followed by an object containing a specific key within an array of objects

Imagine having an array of dictionaries like the one below. How can I locate the object with id: 121 using JavaScript? I've been struggling to figure this out and would appreciate any hints or algorithms on how to achieve this. The desired result sho ...

Executing Ionic function before application shutdown

Does anyone know of a function that can be triggered when the app is about to exit, close, or go into the background? Essentially any event that indicates "the user has stopped using the app"? In my app, I create a 'user log' that keeps track of ...