This is a migrated thread and some comments may be shown as answers.
How to send data to grid client side for set_dataSource method
10 Answers 313 Views
This is a migrated thread and some comments may be shown as answers.
Saima Gul
Top achievements
Rank 1
Saima Gul asked on 14 Jun 2010, 12:00 PM
Hi
In order to get better performance i want to use client side binding in data grid . i read numerous articles and also see demos
and read this thread

but the problem is in demo no method is using  masterTable.set_dataSourc but actually they provide demo for web services or with LinQ to SQLClasses
if i want to use following method as described in documentation
function assignDataSource()
{
var masterTable = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
  masterTable.set_dataSource(<some_data_source_of_the_specified_type_above>);
masterTable.dataBind();
}

i want to know how pass JSON data to this method. What would be written in class either it pass data set or data table and how it will be converted toJSOn. Please give me complete sample code for this

10 Answers, 1 is accepted

Sort by
0
Accepted
Yavor
Telerik team
answered on 17 Jun 2010, 07:54 AM
Hi Saima Gul,

You can pass the data directly on the client, as shown in the following code snippet:

<script type="text/javascript">
   function pageLoad() {
       var data =
        [
           { "ID": 1, "Text": "Text1" },
           { "ID": 2, "Text": "Text2" }
        ];
       var mtv = $find("RadGrid1").get_masterTableView();
       mtv.set_dataSource(data);
       mtv.dataBind();
   }
</script>

Naturally, the data must adhere to the JSON syntax requirements.
I hope this information helps.

Best wishes,
Yavor
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
AMS
Top achievements
Rank 1
answered on 20 Sep 2010, 01:45 PM
Hi Yavor
I am using the same method for binding data returned from json to the client side.
I am using the following code:

$.ajax({
            type: "POST",
            url: getAppPath() + "Account.aspx/UsersList",
            data: { State: StateVal, County: CountyVal, District: DistrictVal, School: SchoolVal, sUserName: userName, sUserEmail: email, Status: StatusVal },
            success: function(results) {
                //alert(results);
                updateGrid(results);
            },
            error: function(msg) {
                alert("The following error occurred: " + msg.status + ": " + msg.statusText);
            }

        });

 <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">

        <script type="text/javascript">
            function fillGrid(items) {
                var tableView = $find("<%= grdUsers.ClientID %>").get_masterTableView();
                tableView.set_dataSource(items);
                tableView.dataBind();
            }


            function updateGrid(result) {

                var a = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
                var tableView = $find("<%= grdUsers.ClientID %>").get_masterTableView();
                tableView.set_dataSource(result);
                tableView.dataBind();
            }

            function RadGrid1_Command(sender, args) {
                
                var a = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
                args.set_cancel(true);
                alert("page command");

            }


        
    
        </script>

    </telerik:RadCodeBlock>

When i call the updateGrid method
                var a = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
the following line returns null. However if i only use this line, it will find the Grid.
var a = $find("<%= RadGrid1.ClientID %>")
Please let me know how to handle it
Thanks.


0
Tsvetoslav
Telerik team
answered on 24 Sep 2010, 06:20 AM
Hello Abbid ,

At what point are you sending the ajax request through jQuery? Have you specified any columns for the grid? Could you provide your complete mark-up and code behind including the UserList page.

Thanks.

Regards,
Tsvetoslav
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
AMS
Top achievements
Rank 1
answered on 24 Sep 2010, 07:17 AM
<!--Hi Tsvetoslav here is the complete code for your convenience -->

<
asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server" EnableScriptCombine="true">
    </telerik:RadScriptManager>
    <%= Html.ScriptInclude("scdsDDLs.js")%>
    <%= Html.ScriptInclude("usersList.js") %>
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
 
        <script type="text/javascript">
            var tableView;
 
            function pageLoad(sender, args) {
                tableView = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
            }
 
            function updateGrid(result) {
 
                /*
                var a = $find('<%= RadGrid1.ClientID %>');
                var b = a.get_masterTableView();
 
                var tableView = $find("<%= grdUsers.ClientID %>").get_masterTableView();
                */
                 
                tableView.set_dataSource(result);
                tableView.dataBind();
            }
 
            function RadGrid1_Command(sender, args) { } //for initializing grid on client side
             
             
            function RadGrid1_Creating(sender, args) {
                var test = sender.get_masterTableView();
                alert("grid creating event");
            }
            function RadGrid1_MasterTableView(sender, args) {
                var test = sender.get_masterTableView();
            }
</script>
 
    </telerik:RadCodeBlock>
 
<div class="gridViewOuter">
        <h1>
            User's List</h1>
        <telerik:RadGrid ID="RadGrid1" runat="server" Skin="Web20" AutoGenerateColumns="false"
            AllowPaging="true">
            <MasterTableView TableLayout="Fixed">
                <Columns>
                    <telerik:GridBoundColumn DataField="Username" HeaderText="User Name" />
                    <telerik:GridBoundColumn DataField="Email" HeaderText="Email" />
                </Columns>
            </MasterTableView>
           <ClientSettings>
                <ClientEvents  OnCommand="RadGrid1_Command" />
            </ClientSettings>
        </telerik:RadGrid>
</asp:Content>
<!--- code for search -->
   $("#ancSearch").click(function() {
        //$(this).parents('form').submit(); //previous method which is simply posting the data for search. Now we have to return Json
        var StateVal = $("#State option:selected").val();
        var CountyVal = $("#County option:selected").val();
        var DistrictVal = $("#District option:selected").val();
        var SchoolVal = $("#School option:selected").val();
        var userName = $("#sUserName").val();
        var email = $("#sUserEmail").val();
        var StatusVal = $("#Status option:selected").val();
 
        $.ajax({
            type: "POST",
            url: getAppPath() + "Account.aspx/UsersList",
            data: { State: StateVal, County: CountyVal, District: DistrictVal, School: SchoolVal, sUserName: userName, sUserEmail: email, Status: StatusVal },
            success: function(results) {
                //alert(results);
                updateGrid(results);
            },
            error: function(msg) {
                alert("The following error occurred: " + msg.status + ": " + msg.statusText);
            }
 
        });
    });
//Controller method
 
   [Authenticate]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult UsersList(FormCollection formData, int? pID)
        {
            try {
 
                ViewData["UserProfile"] = Utils.GetUser(HttpContext);
 
                if (formData["action"] == "activateAll")
                {
                    ActivateAll();
                }
 
                string scds = "";
                string uName = "";
                string uEmail = "";
                bool stat = true;
 
 
                if (formData["State"] == "-1")
                {
                    scds = "00000000000000000";
 
                }
                else if (formData["State"] != "-1" && formData["County"] == "-1")
                {
                    scds = formData["State"];
 
                }
                else if (formData["County"] != "-1" && formData["District"] == "-1")
                {
                    scds = formData["County"];
 
                }
                else if (formData["District"] != "-1" && formData["School"] == "-1")
                {
                    scds = formData["District"];
 
                }
                else
                {
                    scds = formData["School"];
 
                }
 
                //pass the current user's scds in case the user has not selected anything
                if (scds == "00000000000000000")
                {
                    scds = Utils.GetUser(HttpContext).SCDS.ToString();
                }
 
                ViewData["scds"] = scds;
 
                 
                if (formData["sUserName"] != "")
                {
                    uName = formData["sUserName"];
                }
                else if (formData["sUserEmail"] != "")
                {
                    uEmail = formData["sUserEmail"];
                }
                if (formData["Status"] == "1")
                    stat = true;
                else
                    stat = false;
 
 
                FillDropDownListStatus("1");
 
                //var results = new UserProfileModel().GetUsersList(pID.GetValueOrDefault(), scds, uName, uEmail, stat).ToList();
                var results = (from u in new UserProfileModel().GetUsersList(pID.GetValueOrDefault(), scds, uName, uEmail, stat)
                               select new
                               {
                                   FirstName = u.FirstName + " " + u.LastName,
                                   UserName = u.Username,
                                   Email = u.Email,
                                   Status = u.IsActive
                               }).ToList();
 
                return Json(results);

            }
            catch (Exception ex)
            {
                throw ex;
            }
 
        }

if i declare the OnCommand event of grid in order to initialize it like this, i am getting the following error

Control 'ctl00_MainContent_RadGrid1_ctl00_ctl02_ctl01_ctl04' of type 'Button' must be placed inside a form tag with runat=server.

Please do not suggest me to use Telerik MVC Grid for this, as its not possible for me at this stage of my application to replace my Grids and other controls with Telerik MVC controls.

Thanks
0
M.
Top achievements
Rank 1
answered on 27 Sep 2010, 11:07 PM
Hi Yavor, 

may i ask you a favor. I took your example and tried to fit it to my needs. But if i try to update the grid with a data-object only two empty rows are added to the grid table.

I have an RadGrid on my aspx-page that i want to update / rebind from a webservice. My RadGrid looks like this: 

<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" Height="200px" Width="300px">   
      <telerik:RadGrid ID="cartRadGrid1"
          OnItemCreated="cartRadGrid1_ItemCreated"              
          runat="server"
          AllowPaging="True">
          <PagerStyle Mode="NumericPages" />
          <MasterTableView
              AutoGenerateColumns="False"
              DataKeyNames="RecordID"
              ClientDataKeyNames="RecordID"
              Width="100%"
              CommandItemDisplay="None"
              PageSize="3">
              <Columns>
                  <telerik:GridBoundColumn
                      DataField="RecordID" 
                      HeaderText="RecordID"
                      ReadOnly="True"
                      SortExpression="RecordID"                            
                      UniqueName="RecordID"
                      Visible="false">
                  </telerik:GridBoundColumn>
                  <telerik:GridBoundColumn
                      DataField="ARAGRNR"
                      HeaderText="ARAGRNR"
                      SortExpression="ARAGRNR"
                      UniqueName="ARAGRNR"
                      Visible="false">
                  </telerik:GridBoundColumn
                  <telerik:GridTemplateColumn UniqueName="TemplateColumn">
                    <HeaderTemplate></HeaderTemplate>
                    <ItemTemplate>
                      <%# DataBinder.Eval(Container.DataItem, "Manufacturer")%><br />
                      <%# DataBinder.Eval(Container.DataItem, "Productname")%>
                    </ItemTemplate>
                  </telerik:GridTemplateColumn>
 
                  <telerik:GridTemplateColumn UniqueName="TemplateEditColumn">
                    <HeaderTemplate></HeaderTemplate>
                    <ItemTemplate>
                        <%# DataBinder.Eval(Container.DataItem, "Quantity")%><br />                                                    
                        <asp:HyperLink ID="EditLink" runat="server" Text="Edit"></asp:HyperLink>
                    </ItemTemplate>
                  </telerik:GridTemplateColumn>                      
              </Columns>
              <CommandItemTemplate>
                  <a href="#" onclick="return ShowInsertForm();">Add New Record</a>
              </CommandItemTemplate>
          </MasterTableView>
          <ClientSettings>
              <Selecting AllowRowSelect="true" />                   
              <ClientEvents OnRowDblClick="RowDblClick" />
          </ClientSettings>    
      </telerik:RadGrid>
</telerik:RadAjaxPanel>

I call my webservice and pass updateGrid as the callback function:

function callCartWebService() {
  Web.ws.CartWebService.GetShoppingCartList(updateGrid);
}

To avoid any wrong formatting of the json-object returned from the webservice i took your example and took the json-object "data" as you can see below:

function updateGrid() {
  var tableView = $find("<%= cartRadGrid1.ClientID %>").get_masterTableView();
  var data =
  [
     {"RecordID":13,"Manufacturer":"IBM","Productname":"foo185""Quantity":4},
     {"RecordID":24,"Manufacturer":"MSFT","Productname":"bar215""Quantity":8},
     {"RecordID":36,"Manufacturer":"UHU","Productname":"upi235""Quantity":12}
  ];
  tableView.set_dataSource(data);
  tableView.dataBind();
}

(Not passing the result-object to updateGrid happens fully intentional). 

But unfortunately the rows in the grid are not updated / replaced with the values from my json-data-object. Even if i add
tableView.dataBind();
var grid = $find("<%= cartRadGrid1.ClientID %>");
grid.repaint();

at the end of my js-function updateGrid the values are not displayed. 
All that changes is that two empty rows are added:

<tr class="rgAltRow" id="cartRadGrid1_ctl00__1"><td></td><td></td></tr>
<tr id="cartRadGrid1_ctl00__2" class="rgRow"><td></td><td></td></tr>

Could you help me out and tell me why the records from the data-object are not written into the grid - does it have to do with template columns - do i have to use the unique name?

What am i missing?

Thanks a lot
Best regards
M.
0
Veli
Telerik team
answered on 29 Sep 2010, 12:00 PM
Hello M.,

You have set Visible="false" for your 2 GridBoundColumns, so they are not rendered. The other 2 columns are GridTemplateColumns. Content in template columns is not automatically created with client-side databinding. You need to use RadGrid's client-side OnRowDataBound event to find the cells corresponding to template columns and set the cell content manually. To do so you first may want to modify your template columns' ItemTemplate to add some HTML elements you can find by ID that will act as value holders. A complete test page you can try would be the following:

<%@ Page Language="C#" AutoEventWireup="true" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
     
    <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
        <script type="text/javascript">
            function pageLoad(sender, args)
            {
                var tableView = $find("<%= cartRadGrid1.ClientID %>").get_masterTableView();
                var data =
                  [
                     { "RecordID": 13, "Manufacturer": "IBM", "Productname": "foo185", "Quantity": 4 },
                     { "RecordID": 24, "Manufacturer": "MSFT", "Productname": "bar215", "Quantity": 8 },
                     { "RecordID": 36, "Manufacturer": "UHU", "Productname": "upi235", "Quantity": 12 }
                  ];
                tableView.set_dataSource(data);
                tableView.dataBind();
            }
 
            function rowDataBound(sender, args)
            {
                var gridItem = args.get_item();
                var record = args.get_dataItem();
 
                var templateCell = gridItem.get_cell("TemplateColumn");
                $get("Manufacturer", templateCell).innerHTML = record.Manufacturer;
                $get("Productname", templateCell).innerHTML = record.Productname;               
 
                var editCell = gridItem.get_cell("TemplateEditColumn");
                $get("Quantity", editCell).innerHTML = record.Quantity;
            }
        </script>
    </telerik:RadScriptBlock>
 
    <div>
        <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" Height="200px" Width="300px">  
              <telerik:RadGrid ID="cartRadGrid1"                 
                  runat="server"
                  AllowPaging="True">
                  <PagerStyle Mode="NumericPages" />
                  <MasterTableView
                      AutoGenerateColumns="False"
                      DataKeyNames="RecordID"
                      ClientDataKeyNames="RecordID"
                      Width="100%"
                      CommandItemDisplay="None"
                      PageSize="3">
                      <Columns>
                          <telerik:GridBoundColumn
                              DataField="RecordID"
                              HeaderText="RecordID"
                              ReadOnly="True"
                              SortExpression="RecordID"                           
                              UniqueName="RecordID"
                              Visible="false">
                          </telerik:GridBoundColumn>
                          <telerik:GridBoundColumn
                              DataField="ARAGRNR"
                              HeaderText="ARAGRNR"
                              SortExpression="ARAGRNR"
                              UniqueName="ARAGRNR"
                              Visible="false">
                          </telerik:GridBoundColumn>
 
                          <telerik:GridTemplateColumn UniqueName="TemplateColumn">
                            <HeaderTemplate></HeaderTemplate>
                            <ItemTemplate>
                              <span id="Manufacturer"></span>
                              <br />
                              <span id="Productname"></span>
                            </ItemTemplate>
                          </telerik:GridTemplateColumn>
  
                          <telerik:GridTemplateColumn UniqueName="TemplateEditColumn">
                            <HeaderTemplate></HeaderTemplate>
                            <ItemTemplate>
                                <span id="Quantity"></span>
                                <asp:HyperLink ID="EditLink" runat="server" Text="Edit"></asp:HyperLink>
                            </ItemTemplate>
                          </telerik:GridTemplateColumn>                     
                      </Columns>
                      <CommandItemTemplate>
                          <a href="#" onclick="return false;">Add New Record</a>
                      </CommandItemTemplate>
                  </MasterTableView>
                  <ClientSettings>
                      <Selecting AllowRowSelect="true" />       
                      <ClientEvents OnRowDataBound="rowDataBound" OnCommand="function() {}" />
                  </ClientSettings>   
              </telerik:RadGrid>
        </telerik:RadAjaxPanel>
    </div>
    </form>
</body>
</html>

Note the empty OnCommand client event handler function. RadGrid requires that an OnCommand event handler be specified if you are using client-side databinding and the grid is not automatically databound to a web service or page method.

Regards,
Veli
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
AMS
Top achievements
Rank 1
answered on 30 Sep 2010, 05:41 AM
Hi Telerik Team

You have answered the question of Mr. M but my question is still unanswered. I have been waiting it for a long time and its getting late. Please reply to my problem

Regards

Abbid
0
Veli
Telerik team
answered on 30 Sep 2010, 07:41 AM
Hello Abbid ,

RadGrid for ASP.NET AJAX used in an ASP.NET MVC does not have all its features supported. You can refer to MVC limitations help topic for ASP.NET AJAX controls. In particular, RadGrid's built-in insert/update/delete, sorting, grouping, filtering, hierarchy or auto-generated columns are not supported. Here is a blog post on how to work around this limitation.

Veli
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Somnath
Top achievements
Rank 1
answered on 29 Aug 2012, 06:26 AM
Hi,

I want to do same things with RadListBox, so please tell me how to do that.

function pageLoad() {
       var data =
        [
           { "ID": 1, "Text": "Text1" },
           { "ID": 2, "Text": "Text2" }
        ];
       var mtv = $find("RadGrid1").get_masterTableView();
       mtv.set_dataSource(data);
       mtv.dataBind();
   }
Like this code.
Please reply.

--
Prakash
0
Shinu
Top achievements
Rank 1
answered on 31 Aug 2012, 07:41 AM
Hi,

With reference to this forum thread.RadListBox doesn't provide client-side binding with declarative data sources.

Thanks,
Shinu.
Tags
Grid
Asked by
Saima Gul
Top achievements
Rank 1
Answers by
Yavor
Telerik team
AMS
Top achievements
Rank 1
Tsvetoslav
Telerik team
M.
Top achievements
Rank 1
Veli
Telerik team
Somnath
Top achievements
Rank 1
Shinu
Top achievements
Rank 1
Share this question
or