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

Ajax Grid Rendering raw data

10 Answers 393 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.
Geoffrey Hudik
Top achievements
Rank 1
Geoffrey Hudik asked on 04 Feb 2010, 04:31 PM
I wanted to ajax-ify my grid's sorting, paging, filtering while leaving the initial load still done via server binding.  Once I switched to using GridModel<T> however my grid no longer renders correctly; the raw json data is being displayed.  Can you advise what I am doing wrong?

Controller:

//[AcceptVerbs(HttpVerbs.Post)] 
        [GridAction] 
        public ActionResult SearchAjax(PrimaryFacilitySearchViewModel model) 
        { 
            var data = PhyRepository.GetPhysicianPrimaryFacilities(ppf => 
                                                                   ppf.Provider.LastNameFirst.Contains( 
                                                                       model.ProviderName.ToUpper())); 
            var list = data.ToList(); 
 
            var viewModelList = Mapper.Map<IList<PhysicianPrimaryFacility>, IList<PrimaryFacilityViewModel>>(list); 
            ViewData["PpfSearchCriteria"] = model; 
 
            return PartialView(new GridModel<PrimaryFacilityViewModel> { Data = viewModelList }); 
            //return PartialView("PrimaryFacilitySearchResults", viewModelList); 
        } 

Search View Page (javascript removed)
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"  
    Inherits="System.Web.Mvc.ViewPage<TWMaintenance.ViewModels.Physician.PrimaryFacilitySearchViewModel>" %> 
 
<asp:Content ID="PpfSearchHeaderContent" ContentPlaceHolderID="TitleContent" runat="server"
    Primary Facility 
</asp:Content> 
 
<asp:Content ID="PpfSearchScriptContent" ContentPlaceHolderID="ScriptContent" runat="server"
    // removed for brevity 
</asp:Content> 
 
<asp:Content ID="PpfSearchMainContent" ContentPlaceHolderID="MainContent" runat="server"
 
    <h2>Provider Primary Facility Search</h2> 
 
    <%  
        // don't use new {routeValue = Model}; that was resulting in null model values passed to search result control 
        using (Ajax.BeginForm("SearchAjax", "PhysicianPrimaryFacility", this.Model,  
           new AjaxOptions { UpdateTargetId = "searchResults"OnBegin = "ShowWaitCursor"OnComplete = "RevertCursor",  
               OnSuccess="SearchSuccess"LoadingElementId = "ajaxLoader" }, new { id = "ppfSearchForm" })) 
       {%> 
 
        <fieldset> 
            <legend>Physician Primary Facility Search</legend> 
            <div style="float: left; width: 100px; padding: 10px;"
            <label for="ProviderName">Provider Name</label> 
            <%= Html.TextBox("ProviderName", string.Empty, new { maxlength = 50style = "width:100px", @class = "required_group" })%> 
            </div> 
             
            <div style="float: left; width: 100px; padding: 10px;"
            <label for="PhyId">Provider Id</label> 
            <%= Html.TextBox("PhyId", string.Empty, new { maxlength = 50style = "width:100px", @class = "required_group" })%> 
            </div> 
             
            <style="clear: left;"
                <br /> 
                <input type="submit" value="Search" id="ppfSearchButton" style="width:75px" /> 
                &nbsp;&nbsp;&nbsp; 
                <input type="button" id="clearCriteriaButton" value="Clear" style="width:75px" /> 
            </p> 
        </fieldset> 
        <div id="ajaxLoader" style="display:none"><img src="<%= Url.Content("~/Content/loading-gears.gif") %>alt="AJAX loader" /></div
         
    <% } %> 
 
    <div id="searchResults"></div> 
</asp:Content> 
 
 
 

Search Results User Control:

<%@ Control Language="C#"  
Inherits="System.Web.Mvc.ViewUserControl<Telerik.Web.Mvc.GridModel<TWMaintenance.ViewModels.Physician.PrimaryFacilityViewModel>>" %> 
<%@ Import Namespace="TWMaintenance.ViewModels.Physician" %> 
  
 <
     Html.Telerik().Grid<PrimaryFacilityViewModel>(Model.Data) 
         .Name("List") 
         .Columns(cols => 
                      { 
                          cols.Add(ppf => ppf.PpfId).Title("Id"); 
                          cols.Add(ppf => ppf.StartDate).Format("{0:MM/dd/yyyy}"); 
                          cols.Add(ppf => ppf.EndDate); 
                          cols.Add(ppf => ppf.FacilityContractFacContractId).Title("Fcon Id"); 
                          cols.Add(ppf => ppf.FacilityContractName).Title("Facility Contract"); 
                          cols.Add(ppf => ppf.ProviderLastNameFirst).Title("Provider"); 
                      }) 
         .Pageable(settings => settings.PageSize(20)) 
         .Sortable() 
         .PrefixUrlParameters(false) 
         .Filterable() 
         .Ajax(ajax => ajax.Action("SearchAjax", "PhysicianPrimaryFacility", ViewData["PpfSearchCriteria"])) 
        .Render(); 
%> 
 

Thanks

10 Answers, 1 is accepted

Sort by
0
Atanas Korchev
Telerik team
answered on 05 Feb 2010, 09:04 AM
Hello Geoffrey Hudik,

The reason is that the method that should output the partial view is decorated with GridAction. The latter transforms the result into JSON. The solution is to have two similar methods - the one will render the HTML of the view and will not have the GridAction attribute. The other will execute the exactly same code but will be decorated with GridAction.

There is one more thing - Ajax.Form does not execute any JavaScript after updating so the grid will not initialize. Thus we need to execute all JavaScript returned by the partial view:

<% using (Ajax.BeginForm("PartialGrid", new AjaxOptions { UpdateTargetId = "results", OnComplete = "onComplete" }))

<script type="text/javascript">
        function onComplete(context) {
            var html = context.get_data();
            var target = context.get_updateTarget();

            $(target).html(html);

            return false;
        }
    </script>

I have attached a running sample showing this approach.

Regards,
Atanas Korchev
the Telerik team

Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
Follow the status of features or bugs in PITS and vote for them to affect their priority.
0
Geoffrey Hudik
Top achievements
Rank 1
answered on 05 Feb 2010, 03:57 PM
Thanks much, getting closer. The issue I have now on filtering, sorting or paging is:

The model item passed into the dictionary is of type 'Telerik.Web.Mvc.GridModel' but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[TWMaintenance.ViewModels.Physician.PrimaryFacilityViewModel]'.


I'm not sure how your example is working really when the partial grid page is binding to enumerable of the view model but the controller is returning a GridModel.  I thought I also had to change the partial view to be of GridModel<T> which I tried but still has the same general problem.

I've taken our project and stripped it down, replacing the DB data access code with a dummy repository and stripping out most other unneccessary files.  It is at least temporarily available at http://dl.dropbox.com/u/235508/TWMaintDemo.zip and it shows the problem.

The other issue I have which is not really addressed by the telerik samples is passing in / persisting data for the ajax controller method. In a real app there would likely not be any "get all orders or all customers" but rather user input for criteria to get a subset of that data.  My initial server binding method takes a PrimaryFacilitySearchViewModel parameter for the needed search criteria data. However with the grid sorting, paging, and filtering not doing a post, I'm not sure how to get that data back to the ajax controller method so it has the info to requery.  For the time being I am storing in Session state but I am not sure I like that approach.  I suppose this may be more of an ASP.NET MVC question than telerik grid question but I am curious what others are doing for this.

Thanks again
0
Atanas Korchev
Telerik team
answered on 06 Feb 2010, 04:21 PM
Hi Geoffrey Hudik,

This is by design - the action method providing data for the ajax operations (paging sorting) should return GridModel. The GridAction attribute then kicks in and converts the data to json after using our linq expression engine to perform all the operations. However for the initial rendering of the partial view you need not to use GridModel. This is what I have done in the demo project.

You can pass custom data to the ajax controller method easily. Please check this online demo which shows how.

Regards,
Atanas Korchev
the Telerik team

Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
Follow the status of features or bugs in PITS and vote for them to affect their priority.
0
Geoffrey Hudik
Top achievements
Rank 1
answered on 09 Feb 2010, 02:51 PM
If you look at the sample I sent, you will see that the Ajax controller method for sorting, paging etc. is already returning GridModel yet I am receiving the error when you run the sample project and page, sort, filter etc.

[GridAction]  
        public ActionResult SearchAjax(PrimaryFacilitySearchViewModel model)  
        {  
            var viewModelList = GetSearchData(model);  
            var viewModel = new GridModel<PrimaryFacilityViewModel>  
                            {  
                                Data = viewModelList  
                            };  
            return PartialView("PrimaryFacilitySearchResults", viewModel);  
        } 
0
Atanas Korchev
Telerik team
answered on 10 Feb 2010, 08:47 AM
Hi Geoffrey Hudik,

You are missing the JavaScript file of the grid which need to be manually included when the grid is output via partial view. Please add this at the end of PrimaryFacilitySearch.aspx:

<% Html.Telerik().ScriptRegistrar().DefaultGroup(group => group
           .Add("telerik.common.js")
           .Add("telerik.grid.js")
           .Add("telerik.grid.filtering.js")); %>
Regards,
Atanas Korchev
the Telerik team

Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
Follow the status of features or bugs in PITS and vote for them to affect their priority.
0
Geoffrey Hudik
Top achievements
Rank 1
answered on 10 Feb 2010, 06:48 PM
Thanks that worked. It also enabled my previous attempt to work of passing the criteria view data in the ajax action method to the controller.
0
Steve
Top achievements
Rank 1
answered on 03 Mar 2010, 06:17 PM
I'm not getting a partial view, I'm getting pure JSON back from this call ?
0
Steve
Top achievements
Rank 1
answered on 03 Mar 2010, 06:48 PM
Ok, found my error as you describe above - it's important to know when to use GridModel

Let's say the first load was based on form inputs.  How do I pass those same form inputs to the ajax call - or is that done automatically?

I get this error though (from FireBug)


0
Atanas Korchev
Telerik team
answered on 04 Mar 2010, 08:09 AM
Hello Steve,

We need more details about your scenario. You can paste the relevant code from the view and  controller.

Greetings,
Atanas Korchev
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
Hugo
Top achievements
Rank 1
answered on 22 May 2012, 07:50 AM
Hi, 

I am working on a similar functionality. Search text box plus a grid on a partial view. I am calling my controller using "Ajax.Beginform()" and 
on the "function onComplete(context)" function,  context does not have "get_data()" nor "get_updateTarget()".

?context.get_data()
Object doesn't support property or method 'get_data'

 I wonder if this has changed since then (this thread is a bit old it seems). I do see that there is a "responseText" property containing the Json data. I am using a method on my controller decorated with [GridAction]. 

I am using MVC 4 and the latest Telerik release.

Thank you!
.
Tags
Grid
Asked by
Geoffrey Hudik
Top achievements
Rank 1
Answers by
Atanas Korchev
Telerik team
Geoffrey Hudik
Top achievements
Rank 1
Steve
Top achievements
Rank 1
Hugo
Top achievements
Rank 1
Share this question
or