Skip Navigation LinksHome / Community & Support / Developer Productivity Tools Forums / Telerik MVC Extensions (superseded) > Grid > Bind grid using Ajax

Answered Bind grid using Ajax

Feed from this thread
  • Sam avatar

    Posted on Apr 3, 2012 (permalink)

    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.

    Reply

  • Dadv Master avatar

    Posted on Apr 4, 2012 (permalink)

    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

    Reply

  • Sam avatar

    Posted on Apr 4, 2012 (permalink)

    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!

    Reply

  • Answer Dadv Master avatar

    Posted on Apr 4, 2012 (permalink)

    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

    Reply

  • Posted on May 24, 2012 (permalink)

    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?

    Reply

  • Dadv Master avatar

    Posted on May 25, 2012 (permalink)

    Hi,

    What the return of GetTaxInfo ? a GridModel?

    Reply

  • Posted on May 25, 2012 (permalink)

    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 

    Reply

  • Dadv Master avatar

    Posted on May 25, 2012 (permalink)

    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.

    Reply

  • Dadv Master avatar

    Posted on May 25, 2012 (permalink)

    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..)

    Reply

  • Posted on May 25, 2012 (permalink)

    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,

    Reply

  • Dadv Master avatar

    Posted on May 25, 2012 (permalink)

    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)

    Reply

Back to Top

Skip Navigation LinksHome / Community & Support / Developer Productivity Tools Forums / Telerik MVC Extensions (superseded) > Grid > Bind grid using Ajax
Related resources for "Bind grid using Ajax"

ASP.NET MVC Grid Features  |  Documentation  |  Demos  |  Telerik TV ]