Domanda

Qualcuno è stato in grado di implementare il plug-in della griglia JQuery, jqGrid? Sto cercando di implementare il paging JSON, e mi sento come se mi stessi avvicinando, ma sono anche sommerso da dettagli insignificanti. Se qualcuno potesse pubblicare del codice di esempio, lo apprezzerei molto.

È stato utile?

Soluzione

Ho trovato il tuo post mentre stavo cercando di farlo per il mio progetto. L'ho fatto funzionare. Per chiunque ne abbia bisogno in futuro, jqGrid non funzionerà immediatamente con JSON e ASP.NET. Devi apportare un paio di piccole modifiche a grid.base.js. Intorno alla linea 829, sostituisci la sezione del caso json con la seguente:

case "json":
    gdata = JSON.stringify(gdata); //ASP.NET expects JSON as a string
    $.ajax({ url: ts.p.url, 
             type: ts.p.mtype, 
             dataType: "json", 
             contentType: "application/json; charset=utf-8", //required by ASP.NET
             data: gdata, 
             complete: function(JSON, st) { if (st == "success") { addJSONData(cleanUp(JSON.responseText), ts.grid.bDiv); if (loadComplete) { loadComplete(); } } }, 
             error: function(xhr, st, err) { if (loadError) { loadError(xhr, st, err); } endReq(); }, 
             beforeSend: function(xhr) { if (loadBeforeSend) { loadBeforeSend(xhr); } } });
    if (ts.p.loadonce || ts.p.treeGrid) { ts.p.datatype = "local"; }
    break;

Quindi aggiungi la seguente funzione:

function cleanUp(responseText) {
    var myObject = JSON.parse(responseText);  //more secure than eval
    return myObject.d;  //ASP.NET special
}

Dovrai anche includere il parser e stringizer JSON . Oltre a lavorare con ASP.NET, questo codice rivisto è anche più sicuro perché la dichiarazione di valutazione è andata.

EDIT: avrei dovuto anche notare che potresti dover apportare modifiche simili a grid.celledit.js, grid.formedit.js, grid.inlinedit.js e grid.subgrid.js .

Altri suggerimenti

Ho appena jTemplates per eseguire il paging lato client con jQuery e ASP.NET. Ho fatto un post sul blog che puoi trovare qui: http: // www .aaron-powell.com / blog.aspx? id = 1209

Viene illustrato come creare un percorso dati basato su modelli, restituire i dati da ASP.NET e quindi implementare una soluzione di paging.

È possibile utilizzare ASP.Net MVC JsonResult per popolare la griglia.

Classe di persona

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime Birthday { get; set; }

    public static IEnumerable<Person> GetABunchOfPeople()
    {
       // Get a bunch of People.
    }
}

Nel tuo controller avresti:

public JsonResult GetABunchOfPeopleAsJson()
{
    var rows = (Person.GetABunchOfPeople()
        .Select(c => new
                         {
                             id = c.ID,
                             cell = new[]
                                        {
                                            c.ID.ToString(),
                                            c.Name,
                                            c.Birthday.ToShortDateString()
                                        }
                         })).ToArray();

    return new JsonResult
               {
                   Data = new
                              {
                                  page = 1,
                                  records = rows.Length,
                                  rows,
                                  total = 1
                              }
               };
}

E la configurazione di jqGrid per l'URL sarebbe:

url: '<%= ResolveUrl("~/Person/GetAllPeople") %>',

Sto solo tentando di mettere insieme tutto. La mia prima preoccupazione è semplicemente generare una risposta JSON corretta. La mia classe restituita sembra essere serializzata come una proprietà chiamata 'd' - è una cosa di JQuery o una convenzione del metodo web ASP.Net? Temo che jqGrid cercherà i dati al massimo livello, mentre asp.net li inserirà in una proprietà chiamata 'd':

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static object GetData() {
        TestClass tc = new TestClass() { One = "Hello", Two = "World" };
        return tc;
    }


        $("#divResults").click(function() {
            $.ajax({
                type: "POST",
                url: "GridData_bak.aspx/GetData",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(test) {
                    // Replace the div's content with the page method's return.
                    $("#divResults").text(test.d.One);
                },
                error: function(msg) {
                    $("#divResults").text(msg);
                }
            });
        });

Il plugin flexgrid è piuttosto scarso sulla documentazione, tuttavia in una piccola sezione della pagina demo c'è un tut sulla creazione di un oggetto serializzato json, questo è un po 'fuorviante perché la griglia richiede un formato specifico, ho portato il codice php per l'opzione xml con un po 'di grasso di scimmia puoi fare lo stesso per la formattazione json

ecco la mia porta xml

the setup for the grid
 $("#tableToFlex").flexigrid({
                 url: 'WebService.asmx/getData'}
                   ... *other configs* ...);

considera il seguente codice nella classe webservice.asmx

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Xml)> _
Public Function getData(ByVal page As Integer, _
    ByVal qtype As String, _
    ByVal Query As String, _
    ByVal rp As Integer, _
    ByVal sortname As String, _
    ByVal sortorder As String) As System.Xml.XmlDocument
    'note these parameters are inputted to determine paging and constrains for the   resultant rows

    'Sample list to send to the grid
    Dim list = New List(Of ApplicationStateInformation)
    'Sample row object that holds name , surname , address, idnumber ...
    list.Add(New RowObjects( "test1", "test1", "test1", "12345"))
    list.Add(New RowObjects( "test2", "test2", "test2", "12345"))
    list.Add(New RowObjects( "test3", "test3", "test3", "12345"))
    list.Add(New RowObjects( "test4", "test4", "test4", "12345"))
    'retun a xml doc, as we are using the xml format on the flexgrid

    Dim returnDoc = New System.Xml.XmlDocument()
    returnDoc.Load(New IO.StringReader(ToXmlResult(list)))
    Return returnDoc
End Function

Private Function ToXmlResult(ByVal list As List(Of RowObjects)) As String
    'this is the xml document format the grid understands
    Dim result As String = "<?xml version=""1.0"" encoding=""utf-8""?>" & vbCrLf
    result += "<rows>" & vbCrLf
    result += String.Format("<page>{0}</page>" & vbCrLf, "1")
    result += String.Format("<total>{0}</total>" & vbCrLf, "10")
    For Each item In list
        result += ConvertRowData(item)
    Next
    result += "</rows>" & vbCrLf
    Return result
End Function

Private Function ConvertRowData(ByVal row As RowObjects) As String

    Dim result As String = String.Format("<row id='{0}'>" & vbCrLf, row.IdNumber.ToString)
    'THESE SHOULD BE HTML ENCODED (the format arg) but I left it out
    result += String.Format("<cell><![CDATA[{0}]]></cell>" & vbCrLf, row.Name)
    result += String.Format("<cell><![CDATA[{0}]]></cell>" & vbCrLf, row.Surname)
    result += String.Format("<cell><![CDATA[{0}]]></cell>" & vbCrLf, row.IdNumber)

    result += "</row>" & vbCrLf
    Return result
End Function

la d nel json è una difesa integrata contro un potenziale exploit

esempio Ho scoperto che utilizza mvc

Informazioni complete qui

Penso che tu possa far funzionare jqgrid con json & amp; asp.net senza modificare grid.base.js e altri file jqgrid, devi usare la proprietà datatype per definire la tua chiamata ajax personalizzata e definire un lettore json, jqgrid utilizzerà quindi la tua chiamata e lettore ajax personalizzata ogni volta che la griglia viene ricaricata .

Il processo è simile per xml, basta definire un xmlreader anziché un jsonreader.

Tutte le proprietà del jsonreader sono definite nella documentazione online

Per esempi di tipo di dati personalizzato, vedere " Funzione come tipo di dati " nella pagina di dimostrazione live in " Nuovo in 3.3 "

La mia attrezzatura:

dati: " {'page': '" + gdata.page + " ',' righe ':' " + gdata.rows + " ',' sidx ':' " + gdata.sidx + " ',' sord ':' " + gdata.sord + " ',' nd ':' " + gdata.nd + " ',' _ search ':' " + gdata._search + " ',' searchField ':' " + ts.p.searchdata.searchField + " ',' searchString ':' " + ts.p.searchdata.searchString + " ',' searchOper ':' " + ts.p.searchdata.searchOper + " '} " ;,

successo: funzione (JSON, st) { if (st == " success ") {addJSONData (JSON.d, ts.grid.bDiv); if (loadComplete) {loadComplete (); }}

Installato utilizzando l'evento ajax completo usa l'evento success. in questo modo si impedisce la doppia serializzazione di json.

Solo una cosa che non ho realizzato con l'editing delle celle: Supponiamo che io voglia modificare più celle con lo stesso tipo di dati (int). Ho solo un metodo web! e non riesco a sviluppare uno stesso tipo di dati con un nome diverso! Qualcuno risolve questo tipo di problema?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top