Pergunta

ok, estou de volta. I simplificado totalmente o meu problema para apenas três campos simples e eu ainda estou preso na mesma linha usando o método addJSONData. Estive preso neste por dias e não importa como eu refazer a chamada ajax, a string JSON, blá blá blá ... eu não posso chegar a este trabalho! Eu não posso nem começar a trabalhar em função quando a adição de uma linha de dados manualmente. Alguém pode por favor postar uma amostra de trabalho de jqGrid que trabalha com ASP.NET e JSON? Quer fazer o favor incluem 2-3 campos (string, inteiro e data de preferência?) Eu ficaria feliz em ver uma amostra de trabalho de jqGrid e apenas a adição manual de um objeto JSON usando o método addJSONData. Muito obrigado!! Se algum dia eu começar este trabalho, vou postar um exemplo de código completo para todos os outros postagem a ajuda de ASP.NET, os usuários JSON preso neste também. Novamente. OBRIGADO!!

tbl.addJSONData (objGridData); // err: tbl.addJSONData não é uma função !!

Aqui está o Firebug está mostrando quando eu receber esta mensagem:

• objGridData objeto Total = 1 page = 1 registros = 5 linhas = [5]
? página "1"
Registros "5"
Total "1"
Linhas [Object ID = 1 PARTNERID = BCN, Object ID = 2 PARTNERID = BCN, Object ID = 3 PARTNERID = BCN, 2 mais ... 0 = Objeto 1 = Objeto 2 = Objeto 3 = Objeto 4 = Object]
(Index) 0
(Prop) ID (valor) 1 (Prop) PARTNERID (valor) "BCN" (Prop) DateTimeInserted (valor) Qui 29 maio, 2008 12:08:45 GMT-0700 (Pacific Daylight Time)
* Há mais três linhas

Aqui está o valor da variável tbl (valor) 'Table.scroll'

<TABLE cellspacing="0" cellpadding="0" border="0" style="width: 245px;" class="scroll grid_htable"><THEAD><TR><TH class="grid_sort grid_resize" style="width: 55px;"><SPAN> </SPAN><DIV id="jqgh_ID" style="cursor: pointer;">ID <IMG src="http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images/sort_desc.gif"/></DIV></TH><TH class="grid_resize" style="width: 90px;"><SPAN> </SPAN><DIV id="jqgh_PartnerID" style="cursor: pointer;">PartnerID </DIV></TH><TH class="grid_resize" style="width: 100px;"><SPAN> </SPAN><DIV id="jqgh_DateTimeInserted" style="cursor: pointer;">DateTimeInserted </DIV></TH></TR></THEAD></TABLE>

Aqui é a função completa:

 $('table.scroll').jqGrid({  
    datatype: function(postdata) {    
        mtype: "POST",    
    $.ajax({  
        url: 'EDI.asmx/GetTestJSONString',  
        type: "POST",  
        contentType: "application/json; charset=utf-8",  
        data: "{}",  
        dataType: "text", //not json . let me try to parse  
        success: function(msg, st) {  
            if (st == "success") {                    
                 var gridData;  

                //strip of "d:" notation  
                var result = JSON.parse(msg);   
                for (var property in result) {  
                    gridData = result[property];  
                    break;  
                }  

                var objGridData = eval("(" + gridData + ")"); //creates an object with visible data and structure  
                var tbl = jQuery('table.scroll')[0];  

                alert(objGridData.rows[0].PartnerID); //displays the correct data  

                //tbl.addJSONData(objGridData); //error received: addJSONData not a function  

                //error received: addJSONData not a function (This uses eval as shown in the documentation)  
                //tbl.addJSONData(eval("(" + objGridData + ")"));   

                //the line below evaluates fine, creating an object and visible data and structure  
                //var objGridData = eval("(" + gridData + ")");  
                //BUT, the same thing will not work here  
                //tbl.addJSONData(eval("(" + gridData + ")"));  
                //FIREBUG SHOWS THIS AS THE VALUE OF gridData:  
               // "{"total":"1","page":"1","records":"5","rows":[{"ID":1,"PartnerID":"BCN","DateTimeInserted":new Date(1214412777787)},{"ID":2,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125000)},{"ID":3,"PartnerID":"BCN","DateTimeInserted":new Date(1212088125547)},{"ID":4,"PartnerID":"EHG","DateTimeInserted":new Date(1235603192033)},{"ID":5,"PartnerID":"EMDEON","DateTimeInserted":new Date(1235603192000)}]}"         

            }  
        }  
    });  
    },  
    jsonReader: {  
        root: "rows", //arry containing actual data  
        page: "page", //current page  
        total: "total", //total pages for the query  
        records: "records", //total number of records  
        repeatitems: false,  
        id: "ID" //index of the column with the PK in it   
    },  
    colNames: [  
        'ID', 'PartnerID', 'DateTimeInserted'  
          ],    
    colModel: [    
    { name: 'ID', index: 'ID', width: 55 },    
    { name: 'PartnerID', index: 'PartnerID', width: 90 },  
    { name: 'DateTimeInserted', index: 'DateTimeInserted', width: 100}],  
    rowNum: 10,  
    rowList: [10, 20, 30],  
    imgpath: 'http://localhost/DNN5/js/jQuery/jqGrid-3.4.3/themes/sand/images',  
    pager: jQuery('#pager'),  
    sortname: 'ID',  
    viewrecords: true,  
    sortorder: "desc",  
   caption: "TEST Example")};  
Foi útil?

Solução

Aqui está um exemplo simples ...

Você vai precisar https://github.com/douglascrockford/JSON -js / blob / mestre / json2.js Para que isso funcione ...

e, claro, os arquivos jquery habitual.

Cole este para um webservice

// The lower case properties here are required to be lower case
// I cant find a way to rename them when they are serialized to JSON
// XmlElement("yournamehere") does not work for JSON :(
public class JQGrid
{
    public class Row
    {
        public int id { get; set; }
        public List<string> cell { get; set; }

        public Row()
        {
            cell = new List<string>();
        }
    }

    public int page { get; set; }
    public int total { get; set; }
    public int records { get; set; }
    public List<Row> rows { get; set; }

    public JQGrid()
    {
        rows = new List<Row>();
    }
}


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class MyWebService : System.Web.Services.WebService
{

    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]    
    public JQGrid GetJQGrid(int page, int pageSize, string sortIndex, string sortDirection)
    {
        DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.CONN_STRING, "udsp_GetMyData",pageIndex, pageSize);

        if (ds == null || ds.Tables.Count < 1)
            throw new Exception("Unable to retrieve data.");

        JQGrid jqGrid = new JQGrid();

        int i = 1;
        foreach (DataRow dataRow in ds.Tables[0].Rows)
        {
            JQGrid.Row row = new JQGrid.Row();

            row.id = Convert.ToInt32(dataRow["MyIdColumn"]);

            row.cell.Add(dataRow["MyIdColumn"].ToString());

            row.cell.Add(dataRow["MyColumn"].ToString());


            projectGrid.rows.Add(row);
        }

        jqGrid.page = 1; // Set this when you are actually doing paging... this is just a sample
        jqGrid.records = jqGrid.rows.Count;
        jqGrid.total = jqGrid.rows.Count;  // Set this to total pages in your result...

        return jqGrid;
    }
}

Cole este para sua página aspx

<script type="text/javascript">
function getData(pdata) {
    var params = new Object();
    params.page = pdata.page;
    params.pageSize = pdata.rows;
    params.sortIndex = pdata.sidx;
    params.sortDirection = pdata.sord;


    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/CLM/CLM.asmx/GetProjectGrid2",
        data: JSON.stringify(params),
        dataType: "json",
        success: function(data, textStatus) {
            if (textStatus == "success") {
                var thegrid = $("#testGrid")[0];
                thegrid.addJSONData(data.d);
            }
        },
        error: function(data, textStatus) {
            alert('An error has occured retrieving data!');
        }
    });
}

var gridimgpath = '/clm/css/ui-lightness/images';
$(document).ready(function() {
    $("#testGrid").jqGrid({
        datatype: function(pdata) {
            getData(pdata);
        },
        colNames: ['My Id Column', 'My Column'],
        colModel: [
            { name: 'MyIdColumn', index: 'MyIdColumn', width: 150 },
            { name: 'My Column', index: 'MyColumn', width: 250 }
        ],
        rowNum: 10,
        rowList: [10, 20, 30],
        imgpath: gridimgpath,
        pager: jQuery('#pagerdt'),
        sortname: 'id',
        viewrecords: false,
        sortorder: "desc",
        caption: "Projects",
        cellEdit: false
    });
});
</script>

Outras dicas

Normalmente, quando você começa a 'blá não uma função' erro com jqGrid é porque o módulo correto não foi carregado. A função addJSONData é definido no arquivo grid.base.js. você pode verificar a sua função jqGridInclude () no arquivo jquery.jqGrid.js e certifique-se de que grid.base.js está sendo incluído como parte da inicialização de sua variável de módulos?

Você verificou a variável tbl está ficando referência à instância jqgrid?

Tente adicionar um id para o elemento da tabela e obter a referência para o jqgrid como:

var thegrid = jQuery("#mytableid")[0];

Bem, eu vejo uma coisa errada aqui:

var tbl = jQuery('table.scroll')[0];  
 //tbl.addJSONData(objGridData); //error received: addJSONData not a function  

Se você está realmente querendo saber por que você está recebendo este erro, é porque tbl não tem essa função.

Edit: Fiquei curioso, e verificado se jqGrid adicionado esses métodos para o objeto de referência DOM. e eles fizeram. (I verificada usando firebug aqui: http://trirand.com/jqgrid/jqgrid.html ).

Uma coisa que pode estar acontecendo aqui é que você tem várias tabelas de classe 'rolagem' e seu jquery está retornando a pessoa errada.

Uma vez que temos um monte de perguntas para ASP.NET WebForms e jqGrid, decidimos seguir o caminho "componente" e implementar algo que é muito semelhante ao asp: GridView. Dessa forma, você pode controlar jqGrid usando o conhecido ciclo de vida de página ASP.NET, eventos, fontes de dados, etc.

Você pode ver uma Beta desta linha aqui - mais de 30 amostras disponíveis atualmente:

http://www.trirand.net/demo.aspx

Ele provavelmente vai crescer em produto comercial, bem como (licenças de código aberto estará disponível) se não houver interesse nisso. Enquanto isso, você pode usar refletor de verificar as fontes de referência (até descobrir uma maneira de ter a fonte disponível on-line). Estamos usando SVN para ASP.NET em oposição a GitHub para os js núcleo, por isso temos algum trabalho nesse sentido.

Esperamos que isso ajude a comunidade.

Rumen Stankov Trirand

Esta é uma questão muito antiga, no entanto, eu estava tendo o mesmo problema apenas recentemente. Eu postei como eu conseguido isso em um novo blog que eu estou tentando começar.

Pode haver formas mais limpas de fazer isso, mas isso funcionou para mim. Até agora tenho sido capaz de intensificar a partir deste exemplo com bastante facilidade. Meu próximo obstáculo é conseguir o loadonce ao trabalho.

Você pode encontrar meu exemplo aqui:

http://programming.webdad3.com/?p=3

WebForm está morrendo, por isso temos de nos concentrar sobre as últimas tecnologias como asp.net MVC. Eu descobri um novo asp.net jqgrid integração aqui http://www.techdoubts.net/2017/05/full-integration-dynamic-jqgrid-asp-net-mvc.html

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top