locked
Sending jqGrid Data To MVC Controller Method Via EditUrl RRS feed

  • Question

  • User-1231523685 posted

    Suppose I have an MVC controller method called EditCustDetails and it's signature is as follows:

    public ActionResult EditCustDetails(string oper, CustDetails Model, string region)

    This method is used to implement Edit and Delete of jqGrid rows. I see many people use the "editurl" property in jqGrid to send data to a server side method like the one above for deleting and editing of jqGrid data but personally I would handle this using AJAX.

    My question is if they are not using AJAX, how are the data being passed to this method from jqGrid when using "editurl"?  The jqGrid code I'm looking at contains an editurl property but I don't see any postData property for sending data to the server, so how are the parameters sent to the MVC controller method? 

    Thursday, June 14, 2018 12:52 AM

All replies

  • User1520731567 posted

    Hi gapi555,

    My question is if they are not using AJAX, how are the data being passed to this method from jqGrid when using "editurl"?  The jqGrid code I'm looking at contains an editurl property but I don't see any postData property for sending data to the server, so how are the parameters sent to the MVC controller method? 

    Specify the url where the server accept the posted data. This is done with a option "editurl".

    Actually,it still using AJAX in js reference.

    As the picture shows:

    I make a demo to create a jqGrid and use editurl to edit according to these links:

    http://www.trirand.com/blog/jqgrid/jqgrid.html

    https://www.c-sharpcorner.com/article/using-jqgrid-with-asp-net-mvc/

    We can open F12 developer tool to monitor process.

    When I edit and save,it will execute this line:

    $("#Demogrid").jqGrid('saveRow', "1"); 

    Then it will jump to jquery.jqGrid.js and jquery-3.3.1.js in my project.

    However, the ajax function which can pass data using editurl will be completed in these two js references.

    And then jump to the action in controller which defined in editurl.

    You could refer to the below code:

    Note that: Add jQuery.jqGrid Reference from NuGet package

    Model:

    [Table("Customers")]  
    public class Customers  
    {  
        [Key]  
        public int? CustomerID { get; set; }  
        [Required(ErrorMessage = "Required CompanyName")]  
        public string CompanyName { get; set; }  
        [Required(ErrorMessage = "Required ContactName")]  
        public string ContactName { get; set; }  
        [Required(ErrorMessage = "Required ContactTitle")]  
        public string ContactTitle { get; set; }  
        public string Address { get; set; }  
        [Required(ErrorMessage = "Required City")]  
        public string City { get; set; }  
        public string Region { get; set; }  
        [Required(ErrorMessage = "Required PostalCode")]  
        public string PostalCode { get; set; }  
        [Required(ErrorMessage = "Required Country")]  
        public string Country { get; set; }  
        [Required(ErrorMessage = "Required Phone")]  
        public string Phone { get; set; }  
        public string Fax { get; set; }  
    }     

    View:

    @{
        ViewBag.Title = "jqGrid_Index";
    }
    
    <h2>jqGrid_Index</h2>
    
    <div>
        <table id="Demogrid"></table>
        <div id="pager"></div>
    </div>
    <input type="BUTTON" id="ed1" value="Edit row 13" />
    <input type="BUTTON" id="sved1" disabled='true' value="Save row 13" />
    
    @section scripts{
        <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
        <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
        <script src="~/Scripts/jquery-1.10.2.min.js"></script>
        <script src="~/Scripts/jquery-ui-1.10.0.js"></script>
        <script src="~/Scripts/i18n/grid.locale-en.js"></script>
        <script src="~/Scripts/jquery.jqGrid.js"></script>
        <script>
            $(function () {
    
                $("#Demogrid").jqGrid
                    ({
                        url: "/Home/GetCustomers",
                        datatype: 'json',
                        mtype: 'Get',
                        //table header name
                        colNames: ['CustomerID', 'CompanyName', 'ContactName', 'ContactTitle', 'City', 'PostalCode', 'Country', 'Phone'],
                        //colModel takes the data from controller and binds to grid
                        colModel: [
                            {
                                name: 'CustomerID',
                                editable: true,
                                key: true,
                                hidden: true,
                                search: false
                            },
                            {
                                name: "CompanyName", editable: true, editrules: { required: true }, search: true
                            },
                            {
                                name: 'ContactName', editable: true, editrules: { required: true }, search: true
                            },
                            {
                                name: "ContactTitle", editable: true, editrules: { required: true }, search: false
                            },
                            {
                                name: "City", editable: true, editrules: { required: true }, search: false
                            },
                            {
                                name: "PostalCode", editable: true, editrules: { required: true, number: true }, search: false
                            },
                            {
                                name: "Country", editable: true, editrules: { required: true }, search: false
                            },
                            {
                                name: "Phone", editable: true, editrules: { required: true }, search: false
                            }
                        ],
                        height: '100%',
                        viewrecords: true,
                        caption: 'JQgrid DEMO',
                        emptyrecords: 'No records',
                        rowNum: 10,
                        editurl: '/Home/EditCustomer',
             
                        jsonReader:
                            {
                                repeatitems: false,
                            },
                        autowidth: true
                    })
               
    
            });
    
    
    
                $("#ed1").click(function () {
                    $("#Demogrid").jqGrid('editRow', "1");
                    this.disabled = 'true';
                    $("#sved1").attr("disabled", false);
                });
                $("#sved1").click(function () {
                    $("#Demogrid").jqGrid('saveRow', "1");
                    $("#sved1").attr("disabled", true);
                    $("#ed1").attr("disabled", false);
                });
        </script>
    
    }

    Controller:

      public ActionResult jqGrid_Index()
            {
              
    
                return View();
            }
    
    
            public JsonResult GetCustomers(string sord, int page, int rows, string searchString)
            {
                // Create Instance of DatabaseContext class for Accessing Database.
                TestApplication1Context db = new TestApplication1Context();
    
                //Setting Paging
                int pageIndex = Convert.ToInt32(page) - 1;
                int pageSize = rows;
                var Results = db.Customers.Select(
                    a => new
                    {
                        a.CustomerID,
                        a.CompanyName,
                        a.ContactName,
                        a.ContactTitle,
                        a.City,
                        a.PostalCode,
                        a.Country,
                        a.Phone,
                    });
    
                //Get Total Row Count
                int totalRecords = Results.Count();
                var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
    
                //Setting Sorting
                if (sord.ToUpper() == "DESC")
                {
                    Results = Results.OrderByDescending(s => s.CustomerID);
                    Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
                }
                else
                {
                    Results = Results.OrderBy(s => s.CustomerID);
                    Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
                }
                //Setting Search
                if (!string.IsNullOrEmpty(searchString))
                {
                    Results = Results.Where(m => m.CompanyName == searchString || m.ContactName == searchString);
                }
                //Sending Json Object to View.
                var jsonData = new
                {
                    total = totalPages,
                    page,
                    records = totalRecords,
                    rows = Results
                };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
    
            }
    
         
    
            public string EditCustomer(Customers customers)
            {
                string msg;
                try
                {
                    if (ModelState.IsValid)
                    {
                        using (TestApplication1Context db = new TestApplication1Context())
                        {
                            db.Entry(customers).State = EntityState.Modified;
                            db.SaveChanges();
                            msg = "Saved Successfully";
                        }
                    }
                    else
                    {
                        msg = "Some Validation ";
                    }
                }
                catch (Exception ex)
                {
                    msg = "Error occured:" + ex.Message;
                }
                return msg;
            }

    Best Regards.

    Yuki Tao

    Friday, June 15, 2018 9:04 AM
  • User-1231523685 posted

    Hi Yuki,

    Thank you so much for putting a lot of effort into your reply. It really helped to clarify things better than just describing the process through words. However, you still did not show how each variable from jqGrid is marked to be passed to the backend. 

    Normally I see the parameters to be posted to the backend listed in postData separated by commas.  In your example you only have one variable sent to the backend, what if I want to send a couple more data like the ones shown below how would I send them?

    var Ids =[{id:"abc123"},{id:"def332"},{id:"hgd523"}]
    //Send to controller method
    var custIds = JSON.stringyfy(Ids);

    var operations =[{oper:"del"},{oper:"save"},{oper:"edit"}]
    // Send to controller method
    var oper = JSON.stringyfy(operations);





    Friday, June 15, 2018 11:33 AM
  • User-474980206 posted

    I don't really like jqGrids implementation, but its pretty simple. the grid data is stored as the actual <td> html. to send the data to the server, it just creates and object based on its column schema. the properties are the column names, and the value is the matching <td>'s text() for the row.  jqGrid was designed to post xml, so its schema is an xml schema, but its support json also.

    there are two way to add data to the post back, add a hidden column, or add a query parameter to the edit url. 

    note: its been years since I've used jqGrid, but the docs look the same. and as always the source code is the best docs:

       https://github.com/tonytomov/jqGrid

     

    Saturday, June 16, 2018 8:06 PM