locked
crud operations with jqgrid in .net core RRS feed

  • Question

  • User-1202579601 posted
    image link- https://imgur.com/OKUSTul 
    [Authorize(Roles = "Staff")] public string Create([Bind("CertificateType,Event,Venue,Dop,Interval")] Certificate Certificate) { string msg="xxx"; var sid = HttpContext.Session.GetInt32("staffId"); if (sid != null) { staffid = (int)HttpContext.Session.GetInt32("staffId"); Certificate.Status = false; Certificate.StaffId = staffid; try { if (ModelState.IsValid) { _context.Add(Certificate); _context.SaveChanges(); msg = "Saved Successfully"; } else { msg = "Validation data not successfully"; } } catch (Exception ex) { msg = "Error occured:" + ex.Message; } } return msg; } [HttpPost, ActionName("Edit")] [ValidateAntiForgeryToken] [Authorize(Roles = "Manager")] public string Edit(Certificate cert) { string msg; var CertificateToUpdate = _context.Certificates.SingleOrDefault(p => p.Id == cert.Id); Certificate certupd = (Certificate)CertificateToUpdate; if(certupd!=null) certupd.Status = true; _context.SaveChanges(); msg = "Saved Successfully"; return msg; } // POST: Certificates/Delete/5 // [Authorize(Roles = "Admin")] [HttpPost] [ValidateAntiForgeryToken] public string Delete(int pid) { Certificate qcert = _context.Certificates.Find(pid); _context.Certificates.Remove(qcert); _context.SaveChanges(); return "Deleted successfully"; } //jqgrid navgrid part $("#jqGrid1").navGrid("#jqGridPager1", { edit: true, add: true, del: true, search: true, refresh: true,align: "left" }, { url: '@Url.Action("Edit", "Certificates")', editCaption: "The Edit Dialog", recreateForm: true, //checkOnUpdate : true, //checkOnSubmit : true, beforeSubmit: function (postdata, form, oper) { if (confirm('Are you sure you want to update this row?')) { // do something return [true, '']; } else { return [false, 'You can not submit!']; } }, closeAfterEdit: true, errorTextFormat: function (data) { return 'Error: ' + data.responseText } }, // options for the Add Dialog { url: '@Url.Action("Create", "Certificates")', closeAfterAdd: true, recreateForm: true, errorTextFormat: function (data) { return 'Error: ' + data.responseText } }, // options for the Delete Dailog { url: '@Url.Action("Delete", "Certificates")', errorTextFormat: function (data) { return 'Error: ' + data.responseText } } );

    the crud dialogs not firing in the jqgrid.

    Monday, November 16, 2020 2:54 PM

Answers

  • User-1330468790 posted

    Hi pmdrait,

     

    Sorry for the late reply. I am managing to provide you with an one-shot solution since you might not familar with jqGrid. (The codes are copied as an example demo).

     

    First of all, empty-rows problem is related to fetching values from server side. I test the codes from my side using a simulation of data and find that asp.net core always returns json data with camelCase (e.g. customerID) while we set the matching properties with PascalCase (e.g. CustomerID).

    Solution: you could either change global Json serialization settings or only for one action

    Global

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    }

    Action:

    public IActionResult GetCustomers()
            {
                List<Customer> list = database;
                
                return Json( new { rows = list }, new JsonSerializerOptions { PropertyNamingPolicy = null });
            }

     

    Secondly, if you directly use the option 'loadonce: true' in the js side, you might not be able to get grid refreshed since the datatype will be switched automatically to 'local' after the server response will be processed by jqGrid.

    Solution: Change the datatype to its original type, e.g. 'json', then the grid should do a refresh after form submission.

    example code:

    afterSubmit: function () {
                        $('#jqGrid').jqGrid("setGridParam", { datatype: 'json' });
                        return [true];
                    },

     

    More details, you could refer to below simplified demo.

    JQGridExample cshtml:

    @{
        Layout = null;
    }
    
    <h3>JQGrid Example</h3>
    
    <div style="margin-left:20px">
        <table id="jqGrid"></table>
        <div id="jqGridPager"></div>
    </div>
    
    
    <!-- JQuery   -->
    
    <!-- locale for en -->
    <!-- Javascript file of jqGrid --> <!-- JQuery UI --> <!-- JQGrid CSS --> <script type="text/javascript"> $(document).ready(function () { $("#jqGrid").jqGrid({ url: '@Url.Action("GetCustomers", "Home")', // we set the changes to be made at client side using predefined word clientArray //editurl: '@Url.Action("Edit", "Home")', datatype: "json", colModel: [ { label: 'Customer ID', name: 'CustomerID', width: 75, key: true, editable: true, editrules: { required: true } }, { label: 'Company Name', name: 'CompanyName', width: 140, editable: true // must set editable to true if you want to make the field editable }, { label: 'Phone', name: 'Phone', width: 100, editable: true }, { label: 'Postal Code', name: 'PostalCode', width: 80, editable: true }, { label: 'City', name: 'City', width: 140, editable: true } ], sortname: 'CustomerID', sortorder: 'asc', loadonce: true, viewrecords: true, width: 780, height: 200, rowNum: 10, pager: "#jqGridPager" }); $('#jqGrid').navGrid('#jqGridPager', // the buttons to appear on the toolbar of the grid { edit: true, add: true, del: true, search: true, refresh: true, align: "left" }, // options for the Edit Dialog { url: '@Url.Action("Edit", "Home")', editCaption: "The Edit Dialog", recreateForm: true, beforeSubmit: function (postdata, form, oper) { if (confirm('Are you sure you want to update this row?')) { // do something return [true, '']; } else { return [false, 'You can not submit!']; } }, closeAfterEdit: true, errorTextFormat: function (data) { return 'Error: ' + data.responseText }, afterSubmit: function () { $('#jqGrid').jqGrid("setGridParam", { datatype: 'json' }); return [true]; }, reloadAfterSubmit: true, afterComplete: function(response, postdata, formid) { alert(response.responseText); } }, // options for the Add Dialog { url: '@Url.Action("Create", "Home")', closeAfterAdd: true, recreateForm: true, errorTextFormat: function (data) { return 'Error: ' + data.responseText }, reloadAfterSubmit: true, afterComplete: function (response, postdata, formid) { alert(response.responseText); }, afterSubmit: function () { $('#jqGrid').jqGrid("setGridParam", { datatype: 'json' }); return [true]; } }, // options for the Delete Dailog { url: '@Url.Action("Delete", "Home")', errorTextFormat: function (data) { return 'Error: ' + data.responseText }, reloadAfterSubmit: true, afterComplete: function (response, postdata, formid) { alert(response.responseText); }, afterSubmit: function () { $('#jqGrid').jqGrid("setGridParam", { datatype: 'json' }); return [true]; } }); }); </script>

    Controller:


     public static List<Customer> _database;
            public static List<Customer> database
            {
                set
                {
                    _database = value;
                }
                get
                {
                    if (_database is null)
                    {
                        _database = new List<Customer>
                        {
                            new Customer
                            {
                                CustomerID = "ALFKI",
                                CompanyName = "Alfreds Futterkiste",
                                Phone = "030-0074321",
                                PostalCode = "12209",
                                City = "Berlin"
                            },
                            new Customer
                            {
                                CustomerID = "ANATR",
                                CompanyName = "Ana Trujillo Emparedados y helados",
                                Phone = "(5) 555-4729",
                                PostalCode = "050216",
                                City = "M\u00e9xico D.F."
                            }
                        };
                        
                    }
                    return _database;
                }
            }


    public IActionResult JQGridExample() { return View(); } public IActionResult GetCustomers() { List<Customer> list = database; return Json( new { rows = list }, new JsonSerializerOptions { PropertyNamingPolicy = null }); } public string Create(Customer customer) { string msg = "xxx"; if (ModelState.IsValid) { database.Add(customer); msg = "Saved Successfully"; } else { msg = "Validation data not successfully"; } return msg; } [HttpPost, ActionName("Edit")] public string Edit(Customer cert) { string msg; for(int i = 0; i < database.Count(); i++) { if(database[i].CustomerID == cert.CustomerID) { database[i] = cert; } } msg = "Saved Successfully"; return msg; } [HttpPost] public string Delete(string id) { for (int i = 0; i < database.Count(); i++) { if (database[i].CustomerID == id) { database.RemoveAt(i); } } return "Deleted"+ id +"successfully"; }

    Customer model:

     public class Customer
        {
            public string CustomerID { set; get; }
            public string CompanyName { set; get; }
    
            public string Phone { set; get; }
    
            public string PostalCode { set; get; }
    
            public string City { set; get; }
    
    
        }

     Demo:

     

    Hope helps.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 17, 2020 7:25 AM

All replies

  • User-1330468790 posted

    Hi pmdrait,

     

    Sorry for the late reply. I am managing to provide you with an one-shot solution since you might not familar with jqGrid. (The codes are copied as an example demo).

     

    First of all, empty-rows problem is related to fetching values from server side. I test the codes from my side using a simulation of data and find that asp.net core always returns json data with camelCase (e.g. customerID) while we set the matching properties with PascalCase (e.g. CustomerID).

    Solution: you could either change global Json serialization settings or only for one action

    Global

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    }

    Action:

    public IActionResult GetCustomers()
            {
                List<Customer> list = database;
                
                return Json( new { rows = list }, new JsonSerializerOptions { PropertyNamingPolicy = null });
            }

     

    Secondly, if you directly use the option 'loadonce: true' in the js side, you might not be able to get grid refreshed since the datatype will be switched automatically to 'local' after the server response will be processed by jqGrid.

    Solution: Change the datatype to its original type, e.g. 'json', then the grid should do a refresh after form submission.

    example code:

    afterSubmit: function () {
                        $('#jqGrid').jqGrid("setGridParam", { datatype: 'json' });
                        return [true];
                    },

     

    More details, you could refer to below simplified demo.

    JQGridExample cshtml:

    @{
        Layout = null;
    }
    
    <h3>JQGrid Example</h3>
    
    <div style="margin-left:20px">
        <table id="jqGrid"></table>
        <div id="jqGridPager"></div>
    </div>
    
    
    <!-- JQuery   -->
    
    <!-- locale for en -->
    <!-- Javascript file of jqGrid --> <!-- JQuery UI --> <!-- JQGrid CSS --> <script type="text/javascript"> $(document).ready(function () { $("#jqGrid").jqGrid({ url: '@Url.Action("GetCustomers", "Home")', // we set the changes to be made at client side using predefined word clientArray //editurl: '@Url.Action("Edit", "Home")', datatype: "json", colModel: [ { label: 'Customer ID', name: 'CustomerID', width: 75, key: true, editable: true, editrules: { required: true } }, { label: 'Company Name', name: 'CompanyName', width: 140, editable: true // must set editable to true if you want to make the field editable }, { label: 'Phone', name: 'Phone', width: 100, editable: true }, { label: 'Postal Code', name: 'PostalCode', width: 80, editable: true }, { label: 'City', name: 'City', width: 140, editable: true } ], sortname: 'CustomerID', sortorder: 'asc', loadonce: true, viewrecords: true, width: 780, height: 200, rowNum: 10, pager: "#jqGridPager" }); $('#jqGrid').navGrid('#jqGridPager', // the buttons to appear on the toolbar of the grid { edit: true, add: true, del: true, search: true, refresh: true, align: "left" }, // options for the Edit Dialog { url: '@Url.Action("Edit", "Home")', editCaption: "The Edit Dialog", recreateForm: true, beforeSubmit: function (postdata, form, oper) { if (confirm('Are you sure you want to update this row?')) { // do something return [true, '']; } else { return [false, 'You can not submit!']; } }, closeAfterEdit: true, errorTextFormat: function (data) { return 'Error: ' + data.responseText }, afterSubmit: function () { $('#jqGrid').jqGrid("setGridParam", { datatype: 'json' }); return [true]; }, reloadAfterSubmit: true, afterComplete: function(response, postdata, formid) { alert(response.responseText); } }, // options for the Add Dialog { url: '@Url.Action("Create", "Home")', closeAfterAdd: true, recreateForm: true, errorTextFormat: function (data) { return 'Error: ' + data.responseText }, reloadAfterSubmit: true, afterComplete: function (response, postdata, formid) { alert(response.responseText); }, afterSubmit: function () { $('#jqGrid').jqGrid("setGridParam", { datatype: 'json' }); return [true]; } }, // options for the Delete Dailog { url: '@Url.Action("Delete", "Home")', errorTextFormat: function (data) { return 'Error: ' + data.responseText }, reloadAfterSubmit: true, afterComplete: function (response, postdata, formid) { alert(response.responseText); }, afterSubmit: function () { $('#jqGrid').jqGrid("setGridParam", { datatype: 'json' }); return [true]; } }); }); </script>

    Controller:


     public static List<Customer> _database;
            public static List<Customer> database
            {
                set
                {
                    _database = value;
                }
                get
                {
                    if (_database is null)
                    {
                        _database = new List<Customer>
                        {
                            new Customer
                            {
                                CustomerID = "ALFKI",
                                CompanyName = "Alfreds Futterkiste",
                                Phone = "030-0074321",
                                PostalCode = "12209",
                                City = "Berlin"
                            },
                            new Customer
                            {
                                CustomerID = "ANATR",
                                CompanyName = "Ana Trujillo Emparedados y helados",
                                Phone = "(5) 555-4729",
                                PostalCode = "050216",
                                City = "M\u00e9xico D.F."
                            }
                        };
                        
                    }
                    return _database;
                }
            }


    public IActionResult JQGridExample() { return View(); } public IActionResult GetCustomers() { List<Customer> list = database; return Json( new { rows = list }, new JsonSerializerOptions { PropertyNamingPolicy = null }); } public string Create(Customer customer) { string msg = "xxx"; if (ModelState.IsValid) { database.Add(customer); msg = "Saved Successfully"; } else { msg = "Validation data not successfully"; } return msg; } [HttpPost, ActionName("Edit")] public string Edit(Customer cert) { string msg; for(int i = 0; i < database.Count(); i++) { if(database[i].CustomerID == cert.CustomerID) { database[i] = cert; } } msg = "Saved Successfully"; return msg; } [HttpPost] public string Delete(string id) { for (int i = 0; i < database.Count(); i++) { if (database[i].CustomerID == id) { database.RemoveAt(i); } } return "Deleted"+ id +"successfully"; }

    Customer model:

     public class Customer
        {
            public string CustomerID { set; get; }
            public string CompanyName { set; get; }
    
            public string Phone { set; get; }
    
            public string PostalCode { set; get; }
    
            public string City { set; get; }
    
    
        }

     Demo:

     

    Hope helps.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 17, 2020 7:25 AM
  • User-1202579601 posted

    Jqgrid is getting loaded after using JsonSerializerOptions.  Search and refresh works but

    But add/edit options of navgrid not responding. Add/Edit dialog not working

    Tuesday, November 17, 2020 4:55 PM
  • User-1202579601 posted

    Can we get a sample of jqgrid with dropdownlist loaded from db, enum data, datepicker for column fields in .net core 3

    More material on  such combinations is not available.

    Wednesday, November 18, 2020 3:02 PM
  • User-1330468790 posted

    Hi pmdrait,

     

    I found that you have posted this follow up question in a new thread: https://forums.asp.net/t/2172333.aspx

    I have replied you in that thread so we don't need to handle a duplicated question.

     

    Regarding the dropdownlist in jqGrid, you could consider using 'editoptions' for the property 'colModel'.

    Related sample codes for drop down list: https://stackoverflow.com/a/19427595/12871232

    Related sample codes for date picker: https://stackoverflow.com/a/2155697/12871232

     

    Best regards,

    Sean

    Thursday, November 19, 2020 12:55 PM
  • User-1202579601 posted

    Most of the material seen use editurl of jqgrid feature to  call the crud functions in a single method. In my case crud operations are

    dependent on user role.        jqgrid mtype: Get/Post  is also confusing

    Return type of crud methods, how is it used in client side. Some use return type as bool/string

    Thursday, November 19, 2020 1:34 PM
  • User-1202579601 posted

    anything to do with routing configuration?

    my menu in layout contains- <a asp-area="" asp-controller="Papers" asp-action="Index">Paper</a>

    configure method in startup.cs - app.UseSession();
                app.UseStaticFiles();
                app.UseAuthentication();
                app.UseHttpsRedirection();
                app.UseRouting();
                app.UseCors();
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
                });

    attached model,controller(part of it),view. Unable to find why the crud operations not working from jqgrid navgrid.

    the add/edit/delete form dialogs open, but submit operation gives http status 404 error.

    Sunday, November 22, 2020 3:26 PM