简体   繁体   English

无法在jqgrid中使行进入编辑模式

[英]Unable to get row to edit mode in jqgrid

I used the following 我用了以下

 ondblClickRow: function(){ var row_id = $("#grid").getGridParam('selrow'); jQuery('#grid').editRow(row_id, true); } 

from: 从:

jqGrid Cell Editing - Double Click to Edit? jqGrid单元格编辑-双击进行编辑?

On double clicking I am able to get the alert but the EditRow function simply doesn't work. 双击我可以得到警报,但是EditRow函数根本不起作用。

-------Update----------- -------更新-----------

This is the following code I use onclient side:- 这是我在客户端使用的以下代码:-

 function setJqGridParameters(parsedResult) { var lastSel; $('#list').jqGrid('GridUnload'); $("#list").jqGrid({ colModel: JSON.parse(parsedResult.colModel), colNames: JSON.parse(parsedResult.col), datatype: "jsonstring", datastr: JSON.parse(parsedResult.rows), jsonReader: { repeatitems: false }, gridview: true, rowNum: 10, cmTemplate: { title: false }, //, sortable: false }, viewrecords: false, loadonce: true, loadui: 'block', height: 'auto', autowidth: true, loadtext: "Loading....", pgbuttons: false, pginput: false, pgtext: "", shrinkToFit: false, hoverrows: false, ondblClickRow: function (rowid) { if (rowid && rowid !== lastSel) { $('#list').restoreRow(lastSel); lastSel = rowid; } $(this).jqGrid("editGridRow", rowid, { keys: true, addCaption: "Add Record", editCaption: "Edit Record", bSubmit: "Submit", bCancel: "Cancel", bClose: "Close", saveData: "Data has been changed! Save changes?", bYes: "Yes", bNo: "No", bExit: "Cancel", width: window.screen.width / 3, top: window.screen.height / 4, left: window.screen.availWidth / 3, editUrl: 'TypicalVolume.aspx/UpdateVolumeData', beforeSubmit: function (postData, formid) { //alert(JSON.stringify(postData)); PostDataToServer(postData); $(".ui-widget-overlay").trigger('click'); $('#list').trigger('reloadGrid'); return false; }, afterShowForm: function (formid) { $("#COl1").focus(); //var cm = $(this).jqGrid('getColProp', 'Specialty'); //debugger; } }); // debugger; // var grid = $('#list'); // var myRowData = grid.getRowData(rowid); // grid.editRow(rowid, true); //alert(myRowData['Specialty'] + ' ' + myRowData['SpecialtyName']); }, loadComplete: function () { fixPositionsOfFrozenDivs.call(this); }, onSortCol: function (index, icol, sortorder) { sortColumns(index, icol, sortorder); return 'stop'; } }); resizeColumnHeader.call($("#list")[0]); $("#list").parents('div.ui-jqgrid-bdiv').css("max-height", $(window).height() - $('#pivotGridDiv').offset().top - 60); $("#list").jqGrid('setFrozenColumns'); $("#list").triggerHandler("jqGridAfterGridComplete"); fixPositionsOfFrozenDivs.call($("#list")[0]); $(".s-ico").hide(); var cm = $("#list")[0].p.colModel; $.each($("#list")[0].grid.headers, function (index, value) { var cmi = cm[index], colName = cmi.name; if (cmi.sortable) { $('div.ui-jqgrid-sortable', value.el).css({ cursor: "pointer" }); } }); } function PostDataToServer(Data) { $.ajax({ type: "POST", data: "{" + "Data" + ":" + JSON.stringify(Data) + "}", url: "TypicalVolume.aspx/UpdateVolumeData", //data: JSON.stringify(obj), contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { if (result.d == "null") { RedirectToLogin(); } else { SetValues(result); } }, error: function (result) { $('#loadingIndicator').hide(); alert("getPageLoadData: " + result.responseText); //RedirectToErrorPage(); } }); } 

The SetJqGridParameters() function is called on pageload which sets all parameters of Jqgrid. 在页面加载时调用SetJqGridParameters()函数,该函数设置Jqgrid的所有参数。 I used the PostDataToServer() function to send data to server and write the Db Changes. 我使用PostDataToServer()函数将数据发送到服务器并编写了Db更改。 Note:- If I remove the functionality I get an error of null reference in jqgrid.min.js. 注意:-如果删除功能,则jqgrid.min.js中会出现空引用错误。

----Server Code---- ----服务器代码----

 [System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string UpdateVolumeData(object Data)
{
    string WhereCondition1 = "",WhereCondition2="";
    List<string> UpdateStatements = new List<string>();
    Dictionary<string, string> data = new Dictionary<string, string>();
    data = ToDictionary(Data);
    foreach(KeyValuePair<string,string> entry in data)
    {
        if (entry.Key.ToString() == "MainCol1")
        {
            if (WhereCondition1 == "")
            {
                WhereCondition1 = WhereCondition1 + entry.Key.ToString() + "=" +"'"+ entry.Value.ToString()+"'";
            }
            else
            {
                WhereCondition1 = WhereCondition1 + "," + entry.Key.ToString() + "=" + "'"+entry.Value.ToString()+"'";
            }
        }
        else if (entry.Key.ToString() == "MainCol2")
        {
            if (WhereCondition2 == "")
            {
                WhereCondition2 = WhereCondition2 + entry.Key.ToString() + "=" +"'"+ entry.Value.ToString()+"'";
            }
            else
            {
                WhereCondition2 = WhereCondition2 + "," + entry.Key.ToString() + "=" +"'"+ entry.Value.ToString()+"'";
            }
        }
    }
    foreach (KeyValuePair<string, string> entry in data)
    {
        if (entry.Key.ToString() != "MainCol1" && entry.Key.ToString() != "MainCol2")
        {
            UpdateStatements.Add("Update TypicalVolume set TypicalVolume = " + entry.Value + " where Modality = '" + entry.Key + "' and " + WhereCondition1 + " and " + WhereCondition2);
        }
    }
    //JavaScriptSerializer serializer = new JavaScriptSerializer();
    //var data = serializer.Serialize(Data);
    string sqlstatements = string.Join(" ", UpdateStatements);
    SqlConnection conn = new SqlConnection(sqlConnectionString);
    conn.Open();
    SqlCommand cmd = new SqlCommand(sqlstatements, conn);
    cmd.ExecuteNonQuery();
    conn.Close();
    GridData gd = new GridData();
    gd = GetGridData();
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    return serializer.Serialize(gd);
}

 [System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetDataBySearchCriteria()
{
    try
    {
        HttpContext.Current.Session["RoleID"] = 4;
        if (HttpContext.Current.Session["RoleID"] != null)
        {
            if (!CheckAuthorization()) // Redirect to error page if not authorized
            {
                throw new Exception("Un Authorized Acess");
            }
            else
            {
                HttpContext.Current.Session["TypicalVolumeSession"] = null; 
                if (HttpContext.Current.Session["TypicalVolumeSession"] != null)
                {

                    GridData gd = new GridData();
                    gd = HttpContext.Current.Session["TypicalVolumeSession"] as GridData;
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    GridData gd1 = GetGridData();
                    return serializer.Serialize(gd1);
                }
                else
                {
                    HttpContext.Current.Session["TypicalVolumeSession"] = null;
                    GridData gridData = new GridData();
                    DataSet ds = SqlHelper.ExecuteDataset(sqlConnectionString, CommandType.StoredProcedure, "GetTypicalVolumes");

                   DataTable Datadt = ds.Tables[0];
                    //create col model for jqgrid
                    StringBuilder sbcol = new StringBuilder();
                    sbcol.Append("[");
                    foreach (DataColumn column in Datadt.Columns)
                    {
                        sbcol.Append("\"").Append(column.ColumnName).Append("\",");
                    }
                    sbcol.Remove(sbcol.Length - 1, 1).Append("]");
                    StringBuilder sbcolModel = new StringBuilder();
                    sbcolModel.Append("[");
                    string[] rowAreaFields = "MainCol1,MainCol2".Split(',');

                    //create rowdata for jqgrid
                    foreach (DataColumn column in Datadt.Columns)
                    {
                        if (rowAreaFields.Contains(column.ColumnName.Trim()))//apply style for row area fields
                        {
                            sbcolModel.Append("{\"name\":\"").Append(column.ColumnName.Trim()).Append("\",\"index\":\"").Append(column.ColumnName.Trim()).Append("\",\"classes\":\"colstyle\",\"align\":\"left\",\"editable\":true,\"editoptions\": { \"disabled\": \"disabled\" },\"sortable\":true,\"frozen\":true},");
                        }
                        else
                        {
                            sbcolModel.Append("{\"name\":\"").Append(column.ColumnName.Trim()).Append("\",\"index\":\"").Append(column.ColumnName.Trim()).Append("\",\"align\":\"right\",\"sortable\":false,\"editable\":true,\"width\":\"60px\"},");
                        }

                    }
                    sbcolModel.Remove(sbcolModel.Length - 1, 1);
                    sbcolModel.Append("]");


                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                    Dictionary<string, object> drow;
                    foreach (DataRow dr in Datadt.Rows)
                    {
                        drow = new Dictionary<string, object>();
                        foreach (DataColumn col in Datadt.Columns)
                        {
                            drow.Add(col.ColumnName, dr[col]);
                        }
                        rows.Add(drow);
                    }
                    StringBuilder sbjsonRows = new StringBuilder();
                    sbjsonRows.Append(serializer.Serialize(rows));

                    StringBuilder json = new StringBuilder();
                    json.Append("{").Append("\"rows\":").Append(sbjsonRows.ToString().Trim()).Append("}");
                    json.ToString();
                    gridData.col = sbcol.ToString();
                    gridData.colModel = sbcolModel.ToString();
                    gridData.rows = sbjsonRows.ToString().Trim();
                    return serializer.Serialize(gridData);//serialize and return to ajax method
                }
            }
        }
        else
        {
            return "null";//if session expired
        }
    }
    catch (Exception ex)
    {
        LogError(ex);
        throw;
    }
}

The code is in testing mode its still under development, the code is a template from other pages I have developed so it has used session but its not actually required as of now. 该代码处于测试模式,目前仍在开发中,该代码是我开发的其他页面的模板,因此它已使用会话,但到目前为止尚未真正需要。

Requirement:- I have lots of data. 要求:-我有很多数据。 So I would like to update the db and show the real data from db. 所以我想更新数据库并显示数据库中的真实数据。 Because other users might have updated it. 因为其他用户可能已更新它。 So If possible I might want to load data in a lazy manner where I could load data for say 3 pages and then continue loading in the background(do I have such an option in jqgrid). 因此,如果可能的话,我可能希望以一种懒惰的方式加载数据,在这种方式下,我可以加载例如3页的数据,然后继续在后台加载(jqgrid中是否有这样的选项)。 In case its not feasible loading the whole data is ok. 如果无法加载整个数据,则可以。

Also I wish to make examples in C# and contribute them for other new users in as many ways as possible.So that users can find all documentation and help in one place. 我也想用C#编写示例,并以尽可能多的方式为其他新用户提供示例,以便用户可以在一处找到所有文档和帮助。 Please suggest how can I do that too. 请提出我也可以这样做。

For those who refer this:- This question originally started for editable rows. 对于那些引用此内容的人:-这个问题最初是针对可编辑的行开始的。 The first suggestion I got from @Oleg was sufficient. 我从@Oleg得到的第一个建议就足够了。 Later he found that my code was inconsistent because we used code from different jqgrid and also the server code was non standard (do not use those techniques). 后来他发现我的代码不一致,因为我们使用了来自不同jqgrid的代码,并且服务器代码也不是标准的(请不要使用这些技术)。

To Beginners using jqgrid 初学者使用jqgrid

Please make sure you are using the same jqgrid through out which will help you keep your code consistent. 请确保使用相同的jqgrid,这将帮助您保持代码的一致性。 On the internet you can find different versions of jqgrid, so first make sure whether you want to you use free or commercial version, then go for the latest. 在互联网上,您可以找到jqgrid的不同版本,因此请首先确定要使用免费版本还是商业版本,然后再获取最新版本。

There are a lot of strange things in your code (on both server and client side). 您的代码中有很多奇怪的东西(在服务器端和客户端)。 I don't want to rewrite your code. 我不想重写您的代码。 On the client side you just send the same postdata to the server. 在客户端,您只需将相同的postdata发送到服务器。 You just wrap the data in Data parameter and convert to JSON. 您只需将数据包装在Data参数中,然后转换为JSON。

I just mention some clear problems in your code: 我只是在您的代码中提到了一些明显的问题:

  • You place editUrl on the wrong place and you use wrong name of the option. 您将editUrl放在错误的位置,并且使用了错误的选项名称。 The options of editGridRow should be url . editGridRow的选项应为url The correct place of editurl parameter (!!! not editUrl !!!) is the option of jqGrid (on the same place where colModel , colModel and other). editUrl的选项是editurl参数的正确位置(!!!不是editUrl !!!)(位于colModelcolModel和其他位置的同一位置)。
  • To serialize the data posted duting editing to JSON one should use serializeRowData callback and ajaxRowOptions option if you use inline editing method editRow (see your original text). 要序列化在编辑为JSON时发布的数据,如果您使用内联编辑方法editRow (请参见原始文本),则应使用serializeRowData回调和ajaxRowOptions选项。 If you want to use editGridRow method instead (see UPDATED part of your question), then you need use serializeEditData instead of serializeRowData . 如果要改用editGridRow方法(请参见问题的UPDATED部分),则需要使用serializeEditData而不是serializeRowData
  • Call of inline editing method restoreRow inside of ondblClickRow callback have no sense in case of usage form editing method editGridRow . 在使用表单编辑方法editGridRow情况下,在ondblClickRow回调内部调用内联编辑方法restoreRow没有意义。 The usage of $('#list').trigger('reloadGrid'); $('#list').trigger('reloadGrid'); inside of callback beforeSubmit of form editing have no sense because jqGrid reloads the data automatically after for editing. 表单编辑的回调beforeSubmit内部没有任何意义,因为jqGrid在编辑后会自动重新加载数据。 On the other side reloading of local data (you use datatype: "jsonstring" ) have no sences too. 另一方面,重新加载本地数据 (您使用datatype: "jsonstring" )也没有感觉。
  • you wrote in the comment to your question that you use jqGrid 4.6, but you use fixPositionsOfFrozenDivs method which exist only in free jqGrid . 您在问题的注释中写道,您使用的是jqGrid 4.6,但您使用的是fixPositionsOfFrozenDivs方法,该方法仅在免费的jqGrid中存在。 You should decide which fork of jqGrid you want to use and to use the corresponding options. 您应该确定要使用哪个jqGrid分支,并使用相应的选项。 In case of usage free jqGrid you could use new style of the options of form editing and inline editing (see the wiki article ), which could make your code shorter and easy readable. 在免费使用jqGrid的情况下,您可以使用新样式的表单编辑和内联编辑选项(请参阅wiki文章 ),这可以使您的代码更短,更易读。 On the other side the options will work only for free jqGrid. 另一方面,这些选项仅适用于免费的jqGrid。 Thus it's important to know which fork of jqGrid you use and in which version . 因此,重要的是要知道使用哪个jqGrid分支以及哪个版本
  • I would recommend you to use parameters of SqlCommand and never construct the SQL statement directly as a string (see building of WhereCondition2 in your code). 我建议您使用SqlCommand 参数 ,并且不要直接将SQL语句构造为字符串(请参见代码中WhereCondition2构建)。 It's very dengarous. 这是非常肮脏的。
  • You should never use manual serialization of output data in WebMethod: JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize(gd); 您不应该在WebMethod中使用输出数据的手动序列化: JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize(gd); JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Serialize(gd); . It's wrong! 这是不对的! ASP.NET makes JSON/XML serialization automatically based on Content-Type header of the HTTP request. ASP.NET根据HTTP请求的Content-Type标头自动进行JSON / XML序列化。 The type of returned data should be object instead of string ( public static string GetDataBySearchCriteria() need be replaced to public static object GetDataBySearchCriteria() ). 返回的数据类型应该是object而不是string(需要将public static string GetDataBySearchCriteria()替换为public static object GetDataBySearchCriteria() )。 You should use return gd; 您应该使用return gd; instead of return serializer.Serialize(gd); 而不是return serializer.Serialize(gd); . Your current server method serialize to JSON twice . 您当前的服务器方法两次序列化为JSON。 The string returned by GetDataBySearchCriteria or by UpdateVolumeData will be serialized once more . GetDataBySearchCriteriaUpdateVolumeData返回的字符串将再次进行序列化。 Thus the server returns something like {"d": "{..., \\"some string\\"...}"} instead of {"d": {..., "some string"...}} . 因此,服务器返回的内容类似于{"d": "{..., \\"some string\\"...}"}而不是{"d": {..., "some string"...}} The usage of sbcolModel.Append("{\\"name\\":\\"") and json.Append("{").Append("\\"rows\\":") is very bad too. Correct code should work only with objects . No manual conversion of JSON is required. Only because of that you need include additional call of JSON.parse or $.parseJSON . Typical $.ajax call converts JSON data to object internally and you works directly with object . It's probably the reason why you don't used datatype: "json" and jsonReader: {repeatitems: false}, ajaxGridOptions: { contentType: "application/json" }, serializeGridData: function (postData) { return JSON.stringify(postData); } and so on. sbcolModel.Append("{\\"name\\":\\"")json.Append("{").Append("\\"rows\\":")也很糟糕。正确的代码应该只能工作带对象的对象 ,不需要手动进行JSON转换,仅因为这个原因,您需要包括JSON.parse$.parseJSON附加调用。典型的$.ajax调用将JSON数据内部转换为对象,而您可以直接使用object进行操作 。不使用datatype: "json"原因datatype: "json"jsonReader: {repeatitems: false}, ajaxGridOptions: { contentType: "application/json" }, serializeGridData: function (postData) { return JSON.stringify(postData); }和以此类推。

I can continue... 我可以继续...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM