This is a migrated thread and some comments may be shown as answers.

Grid Not Filling

2 Answers 281 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Steve
Top achievements
Rank 1
Steve asked on 30 Apr 2014, 08:08 PM
I have been working on this the last few days, and am very new to Javascript and Kendo UI.  I have created my WCF and it is working fine. When I go to the URl/FunctionName I get a list of the Employee data returned.  Below is a paste of that data...

[{"FirstName":"Nancy","LastName":"Davolio"},{"FirstName":"Andrew","LastName":"Fuller"},{"FirstName":"Janet","LastName":"Leverling"},{"FirstName":"Margaret","LastName":"Peacock"},{"FirstName":"Steven","LastName":"Buchanan"},{"FirstName":"Michael","LastName":"Suyama"},{"FirstName":"Robert","LastName":"King"},{"FirstName":"Laura","LastName":"Callahan"},{"FirstName":"Anne","LastName":"Dodsworth"}]

However, when I try to get this data using my ASP.NET website project, it does not load correctly.  I dont know if I am doing something wrong in the filling of the grid, or the calling of the WCF itself, so I decided to try to ask here as I am out of ideas.  The errors that come up in Chrome debugger are as follows...

"OPTIONS http://localhost:27689/Service1.svc/GetDataUsingDataContract?_=1398887165670 405 (Method Not Allowed) jquery-1.9.1.js:9597
XMLHttpRequest cannot load http://localhost:27689/Service1.svc/GetDataUsingDataContract?_=1398887165670. Invalid HTTP status code 405"

However, when I click on the http://...... it shows on the browser fine.


Below is a copy of my Web Page Markup. If anyone could please tell me what I am doing wrong, it would be much appreciated.  Below the markup of my page, I am also going to put the Interface of my WCF, the Config of the WCF and the code behind the interface so that just in case that is the issue, someone will have it available to help.  Thanks.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridPage.aspx.cs" Inherits="FlightWebSite.GridPage" %>

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="Styles/kendo.common.min.css" rel="stylesheet" />
    <link href="Styles/kendo.default.min.css" rel="stylesheet" />
    <script src="Scripts/jquery.min.js"></script>
    <script src="Scripts/kendo.all.min.js"></script>

</head>
<body>
    
        <div id="example" class="k-content">
            <div id="clientsDb">

                <div id="grid" style="height: 365px"></div>

            </div>

           <%-- <style scoped>
                #clientsDb {
                    width: 952px;
                    height: 396px;
                    margin: 20px auto 0;
                    padding: 51px 4px 0 4px;
                   // background: url('../../content/web/grid/clientsDb.png') no-repeat 0 0;
                }
            </style>--%>

         
            <script>
                var yourJSONObject;

                var safeLogger = function (msg) {
                    if (window.console && window.console.log)
                        window.console.log(msg);
                }

                //function myfunction(yourJSONObject) {
                //    $.getJSON('http://localhost:27689/Service1.svc/GetDataUsingDataContract', function (data) {
                //        //Parse your JSON object into a Javascript object
                //        yourJSONObject = jQuery.parseJSON(data);

                //        for (var i = 0; i < yourJSONObject.Comment.length; i++) {
                //            safeLogger(yourJSONObject.Comment[i].LastName + ", "
                //            + yourJSONObject.Comment[i].FirstName);
                //        }
                //    })}

                $(document).ready(function () {
                    $("#grid").kendoGrid({
                        dataSource: {
                            type: "odata",
                            transport: {
                                contentType: "application/json; charset=utf-8",
                                read: "http://localhost:27689/Service1.svc/GetDataUsingDataContract",
                                dataType: "json"
                            },
                            schema: {
                                model: {
                                    fields: {
                                        LastName: { type: "string" },
                                        FirstName: { type: "string" }
                                    }
                                },
                                pageSize: 20,
                                serverPaging: true,
                                serverFiltering: true,
                                serverSorting: true
                            },
                            height: 430,
                            filterable: true,
                            sortable: true,
                            pageable: true,
                            columns: [
                                "Employees",
                                {
                                    field: "LastName",
                                    title: "Last Name",
                                    width: 260
                                }, {
                                    field: "FirstName",
                                    title: "First Name",
                                    width: 260
                                }
                            ]
                        }});
                })

            </script>
        </div>


</body>
</html>

WCF Interface

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat= WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        List<Employees> GetDataUsingDataContract();

        [OperationContract]
        string GetData();


        // TODO: Add your service operations here
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class Employees
    {
        string lastName = "";
        string firstName = "";

        [DataMember]
        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }

        [DataMember]
        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }
    }
}


Config File:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
    <services>
        <service  name="WcfService1.Service1" behaviorConfiguration="DefaultServiceBehavior">
            <endpoint binding="webHttpBinding" contract="WcfService1.IService1"      behaviorConfiguration="DefaultEPBehavior" />
        </service>
    </services>
    <behaviors>
        <endpointBehaviors>
            <behavior name="DefaultEPBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="DefaultServiceBehavior">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
    <directoryBrowse enabled="true"/>
</system.webServer>
  
 <connectionStrings>
      <clear />
      <add name="MyConnectionString" 
       providerName="System.Data.ProviderName" 
       connectionString="Integrated Security=SSPI;Initial Catalog=northwind;Data Source=Staley3-PC" />
    </connectionStrings>


</configuration>

Implementation of Functions in interface:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.

    [AspNetCompatibilityRequirements(RequirementsMode =
            AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
        LRUCache<DataSet> lruCache;
        static string GetConnectionStringByName(string name)
        {
            // Assume failure. 
            string returnValue = null;

            // Look for the name in the connectionStrings section.
            ConnectionStringSettings settings =
                ConfigurationManager.ConnectionStrings[name];

            // If found, return the connection string. 
            if (settings != null)
                returnValue = settings.ConnectionString;

            return returnValue;
        }

        /// <summary>
        /// Gets the data from the database and returns it in XML Format
        /// </summary>
        /// <returns></returns>
        public string GetData()
        {
            string xml;
            DataSet dset = new DataSet();
            SqlConnection conn = new SqlConnection(GetConnectionStringByName("MyConnectionString"));
            SqlCommand comm = new SqlCommand("Select * From Employees");
            SqlDataAdapter dAdapt = new SqlDataAdapter(comm);
            dAdapt.Fill(dset);
            ////If we use this way of Caching this caches the data
            //lruCache = new LRUCache<DataSet>(100);
            //lruCache.Add("myDset", dset);

            ////Retrives the data from Cache
            //DataSet dset2 = new DataSet();
            //lruCache.Get("myDset", out dset2);

            xml = dset.GetXml();
            return xml;
        }


        public List<Employees> GetDataUsingDataContract()
        {

           // WebOperationContext.Current.OutgoingResponse.Headers.Add(
           //"Access-Control-Allow-Origin", "*"); 
            WebOperationContext.Current.OutgoingResponse.Headers.Add(
           "Access-Control-Allow-Methods", "GET"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
           "Access-Control-Allow-Headers", "Content-Type, Accept");

            //Fill Dataset with Emolyee Info
            DataSet dset = new DataSet();
            SqlConnection conn = new SqlConnection(GetConnectionStringByName("MyConnectionString"));
            SqlCommand comm = new SqlCommand("Select LastName, FirstName From Employees", conn);
            SqlDataAdapter dAdapt = new SqlDataAdapter(comm);
            dAdapt.Fill(dset);
            

            //Get Data Table out of dataset
            DataTable products = dset.Tables[0];
            
            //use Linq to fill List of employees
            List<Employees> list = dset.Tables[0].AsEnumerable().
                Select(product => new Employees
                {
                    FirstName = product.Field<string>("FirstName"),
                    LastName = product.Field<string>("LastName")
                }).ToList<Employees>();
     
            //Return the List of Employees to Application
            return list;
        }
    }
}

 

2 Answers, 1 is accepted

Sort by
0
Steve
Top achievements
Rank 1
answered on 30 Apr 2014, 08:38 PM
I did see that when I try the folliwng code, in the Chrome Console, that the object is returned from the browser fine.

$.getJSON('http://localhost:27689/Service1.svc/GetDataUsingDataContract', function (data) {
//Parse your JSON object into a Javascript object
yourJSONObject = jQuery.parseJSON(data);

for (var i = 0; i < yourJSONObject.Comment.length; i++) {
safeLogger(yourJSONObject.Comment[i].LastName + ", "
+ yourJSONObject.Comment[i].FirstName);
}

Is there a way to use this yourJSONObject to fill the Kendo Grid and not read from the URL in creation?  Would this solve my problem? If so, can someone help me with code on how to do that?  Thanks.
0
Atanas Korchev
Telerik team
answered on 02 May 2014, 11:50 AM
Hello Steve,

Yes it is possible to bind the Kendo Grid to an array of JavaScript objects. You need to set the data option of its data source:

$("#grid").kendoGrid({
   dataSource: {
         data: yourJSONObject
   }
});

You can also set it after the grid has been initialized:

var grid = $("#grid").data("kendoGrid");

grid.dataSource.data(yourJSONObject);

Regards,
Atanas Korchev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Tags
Grid
Asked by
Steve
Top achievements
Rank 1
Answers by
Steve
Top achievements
Rank 1
Atanas Korchev
Telerik team
Share this question
or