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

[Solved] Bind grid using Ajax

10 Answers 591 Views
Grid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Sam
Top achievements
Rank 1
Sam asked on 03 Apr 2012, 10:43 PM
Hi,

In my Index.cshtml file, I have the following code:

@using (Html.BeginForm("Index", "Home", FormMethod.Post,
    new
    {
        id = "FormID"
    }))
{
    <fieldset>
        <legend>Dist</legend>

        @(Html.Telerik().ComboBox()
            .Name("ComboBox")
            .BindTo((IEnumerable<DropDownItem>)ViewData["Dist"])
            .ClientEvents(events => events.OnChange("ComboBox_onChange"))

        )
 
        @(Html.Telerik().Grid(Model)
            .Name("grid")
            .Columns(columns =>
                {
                    columns.Bound(o => o.OrderId).Width(40);
                })
             .DataBinding(dataBinding => dataBinding.Ajax().Select("OrderList()", "Home"))
            .Render()
        )

    </fieldset>
 }

Also, the following javascript:

<script type="text/javascript">

     function ComboBox_onChange(e) {
         var combobox = $(this).val();
         var grid = $("#grid").data("tGrid");
         $.ajax({
            type: 'POST',
            url: 'http://localhost:54721/Home/OrderList',
            data: "{'Id':'" + combobox + "'}",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data){
                $("#grid").dataBind(data);
               },
            error: OnError
         });
     }

    function OnError(request, status, error) {
        if (x.status == 0) {
            alert('You are offline!!\n Please Check Your Network.');
        } else if (x.status == 404) {
            alert('Requested URL not found.');
        } else if (x.status == 500) {
            alert('Internel Server Error.');
        } else if (e == 'parsererror') {
            alert('Error.\nParsing JSON Request failed.');
        } else if (e == 'timeout') {
            alert('Request Time out.');
        } else {
            alert('Unknow Error.\n' + x.responseText);
        }
    }

     function Grid_onDataBinding(e) {
         var grid = $(this).data('tGrid');
         $.ajax({
             type: 'POST',
             url: 'http://localhost:54721/Home/OrderList',
             data: "{'Id':'" + combobox + "'}",
             contentType: 'application/json; charset=utf-8',
             dataType: 'json',
             success: function (data) {
                 $("#grid").dataBind(data);
             },
             error: OnError
         });
       
    }

 </script>
           
In the controller file, I have this:

       public ActionResult Index()
        {
            //ViewBag.Message = "Welcome to ASP.NET MVC!";
            //ViewBag.Dist = GetDistList();
            var dist = from p in Distributor.DistributorList()
                       select new Telerik.Web.Mvc.UI.DropDownItem
                       {
                           Text = p.Text,
                           Value = p.Value
                       };
            ViewData["Dist"] = dist.ToList();
            return View();

        }

 

The drop down works fine.  What I want to do is when the user pick an record/item from the dropdown, it calls an action from the controller, and populate the grid.  I can see it gets the data but the grid does not show up.  What did I do wrong?  Thanks for your help.

10 Answers, 1 is accepted

Sort by
0
Dadv
Top achievements
Rank 1
answered on 04 Apr 2012, 09:16 AM
I see some stuff, don't know if it is you pb :
.DataBinding(dataBinding => dataBinding.Ajax().Select("OrderList()", "Home")) 
=>.DataBinding(dataBinding => dataBinding.Ajax().Select("OrderList", "Home")) 

and this one (2 time) :

 success: function(data){
                $("#grid").dataBind(data);
               }, 
=>
 success: function(data){
                grid.dataBind(data);
               }, 

also you use server and ajax binding :
@(Html.Telerik().Grid(Model) => server binding
 .DataBinding(dataBinding => dataBinding.Ajax().Select("OrderList", "Home")) => ajax binding

I don't see the OrderList  action so i can't say if it is good or not
0
Sam
Top achievements
Rank 1
answered on 04 Apr 2012, 03:11 PM
Hi Dadv,

I'm very new at this so I'm still trying to undestand.  If I have this code in my controller:

         [GridAction]
        public ActionResult OrderList(string ID)
        {
            return View(OrderListModel.IEnumOrders(ID));
        }


How can I call it by passing the combobox item id to rebind the grid using Ajax?  Can you give me an example?  Thanks!
0
Accepted
Dadv
Top achievements
Rank 1
answered on 04 Apr 2012, 03:46 PM
Well i think you mix a lot of things :

@using (Html.BeginForm("Index", "Home", FormMethod.Post, => this is server side form, if you use Ajax binding in the grid this is probably not necessary

<script type="text/javascript">

     function ComboBox_onChange(e) {
         var combobox = $(this).val();
         var grid = $("#grid").data("tGrid");
        
grid.rebind({ID: combobox}); //rebind with a param the grid, don't need to post the form, the grid will do the job alone
     }

</script>

@(Html.Telerik().Grid<MyModel>()//no need of Model binding here, it's the ajax binding who do the job
            .Name("grid")
            .Columns(columns =>
                {
                    columns.Bound(o => o.OrderId).Width(40);
                })
             .DataBinding(dataBinding => dataBinding.Ajax().Select("OrderList", "Home"))
            .Render()
        ) 


   [GridAction]
        public ActionResult OrderList(string ID)
        {
            return View(GridModel{Data=OrderListModel.IEnumOrders(ID)});//if you want Telerik grid to show the list, you need to return a GridModel object
        } 


I think there are a pb with first load of the grid (what is the initial ID?) but you should find how to solve that i think.
Create on the fly so there are certainly a lot of typo
0
Marco Teodoro
Top achievements
Rank 1
answered on 24 May 2012, 06:39 PM
I have a more complex situation.

i need to send data that will be binded back to a custom c# class.

take this class as sample:

public class Test
   {
       decimal MinTax {get; set;}
       decimal MaxTax {get; set;}
       int MinDays {get; set;}
       int MaxDays {get; set;}
       decimal Montante { get; set; }
       int[] NotSelectedPartners {get; set;}
       int[] NotSelectedPayments {get; set;}
   }

This will be my action:
[GridAction]
public ActionResult GetTaxInfo(Test model)
{
        .........
}

and this will be my javascript on databinding

function Grid_onDataBinding(e) {
        e.data = {
            model: {
                MinTax: 1.2,
                MaxTax: 3,
                MinDays: 1,
                MaxDays: 2,
                Montante: 100,
                NotSelectedPartners: [12, 12, 12],
                NotSelectedPayments: [12, 12, 12]
            }
        };
    }


How can i achieve this behaviour?
0
Dadv
Top achievements
Rank 1
answered on 25 May 2012, 08:19 AM
Hi,

What the return of GetTaxInfo ? a GridModel?
0
Marco Teodoro
Top achievements
Rank 1
answered on 25 May 2012, 09:20 AM
yes. i return a grid model.

But my problem is the client to server communication not server to client. 
I think i would implement it like the following sample. http://demos.telerik.com/aspnet-mvc/razor/grid/externalservicetwitter 
0
Dadv
Top achievements
Rank 1
answered on 25 May 2012, 02:26 PM
My question was to understood the way you want to get the information, anyway you could try something simpler if the value of the "Test" object are fixed :

dataBinding.Ajax().Select("Action", "Controller", new Test{ [your properties]});


If not (value change on client side) then be aware that you MUST be in ajax binding only (not server or mixed binding) ;Documentation

<script type="text/javascript">
functin Grid_onDataBinding(e) {
   
e.data = {
            model: {
                MinTax: 1.2,
                MaxTax: 3,
                MinDays: 1,
                MaxDays: 2,
                Montante: 100,
                NotSelectedPartners: [12, 12, 12],
                NotSelectedPayments: [12, 12, 12]
            }
        };

}
</script>

this is what you wrote but look at your grid data-binding because if you don't use ajax binding (or web service binding), e.data will not be send.


if your code don't work after all, look at the request send (use F12 on IE and Chrome or firebug in FF), some time the data are send but the data format not match the prototype of the C# class, then it's not instantiate.

Look at the return also, sometime an .Net error are include and not send back by the grid error event.
0
Dadv
Top achievements
Rank 1
answered on 25 May 2012, 02:29 PM
an other common error is the mixed mode :

Html.Telerik().Grid(Model)//Server binding
...
DataBinding.Ajax().Select("Action", "Controller")//Ajax binding ONLY on first interaction with the grid (paging, sorting, etc..)

0
Marco Teodoro
Top achievements
Rank 1
answered on 25 May 2012, 03:53 PM
nop i was using just ajax binding. I have looked into firebug to see what was being sended on the wire. All data is sended correctly as json object. but i think telerik model binder does't accept such a complex model. so i change my action signature to send each model parameter. like Action(int param1 , int param2

its ugly but it works... i don't know if someone have find a way to do this but unfortunately i have already lose to much time on this. Maybe later i will look again to this action.

Thanks,
0
Dadv
Top achievements
Rank 1
answered on 25 May 2012, 11:11 PM
It's not telerik who bind the data, it's the MVC framework.

if your json it not translate in the model object then you probably need to look at the "Test" class.

First try to remove the problematic properties :

e.data = {
            model: {
                //MinTax: 1.2,
                //MaxTax: 3, // should probably look like 3.0 for force the decimal operator
                MinDays: 1,
                MaxDays: 2,
               // Montante: 100, // should probably look like 100.0 for force the decimal operator 
                //NotSelectedPartners: [12, 12, 12], // array could sometime create problems
                //NotSelectedPayments: [12, 12, 12]
            }
        };


public class Test
   {
       //decimal MinTax {get; set;}
       //decimal MaxTax {get; set;}
       int MinDays {get; set;}
       int MaxDays {get; set;}
      // decimal Montante { get; set; }
      // int[] NotSelectedPartners {get; set;}
      // int[] NotSelectedPayments {get; set;}
   }

try with 'int' only if you get the object instantiate.


if it's always not working then try to look at the method type (get or post) and force the attribute on the action.

normally, if the empiric method (with params) work, the instantiate one work also, but sometime you need to instantiate some of the properties in the constructor first (array for example, use List instead).

the values are transmit in 'string' and cast after, but sometime the cast don't work if the string is not exactly what the MVC framework want(some decimal <=> long <=> int don't work fine due to the comma)
Tags
Grid
Asked by
Sam
Top achievements
Rank 1
Answers by
Dadv
Top achievements
Rank 1
Sam
Top achievements
Rank 1
Marco Teodoro
Top achievements
Rank 1
Share this question
or