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

[Solved] MVC grid sorting/paging

8 Answers 352 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.
Nebras
Top achievements
Rank 1
Nebras asked on 07 Mar 2011, 10:18 AM
I have a MVC telerik grid which work with server binding
I added a text box to filter it by sending the textbox value to the "Index" method

I want to enable paging and sorting to the grid , but if the grid is filtered by the text box and then press (sort or page)  , the textbox value is passed to "Index" by NULL which means No Filter then the grid is reload all its records without the required filter

any help ? I want to pass the textbox value into "Index" in the sort/pageing case

8 Answers, 1 is accepted

Sort by
0
Accepted
Rosen
Telerik team
answered on 07 Mar 2011, 11:27 AM
Hi Nebras,

In order to achieve the requested functionality, you should modify the DataBinding Select configuration to include the value of the filter. Similar to the following:

Copy Code
<%= Html.Telerik().Grid(Model)
        .Name("Grid")
        .DataBinding(dataBinding => dataBinding.Server()
    .Select("Index","Home", new{filterValue= ViewData["FilterValue"]}))
        .Sortable()
        .Pageable()
%>


Copy Code
public ActionResult Index(string filterValue)
{
    ViewData["FilterValue"] = filterValue;
    var    data; //get the data
    return View(data);
}



Regards,
Rosen
the Telerik team
Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
0
Nebras
Top achievements
Rank 1
answered on 07 Mar 2011, 12:02 PM
It works .. Many Thanks
0
Corey Gaudin
Top achievements
Rank 1
answered on 05 May 2011, 07:33 PM
How would you get this to work with Pure AJAX binding?

I have 3 textboxes that filter the result and use jQuery to grab the results on a Filter Button Click and then do the following:

I am using only Ajax Binding:

View Script Side
        //Handle Filter Click Event
        $('#filterButton').click(function (e) {
                var proposal = $('#Proposal').val();
                var title = $('#ProjectTitle').val();
                var company = $('#CompanyName').val();

                //Rebind the Grid to filter it based on our values
                var grid = $('#Grid').data('tGrid');
                grid.rebind({
                    proposal: proposal,
                    title: title,
                    company: company
                });
        });

View:
<div id="projectList">
    @(Html.Telerik().Grid<ProposalSearchViewModel>()
        .Name("Grid")
        .DataKeys(k => k.Add(m => m.Id))
        .Columns(col => {
            col.Bound(o => o.ProposalNumber).Title("Prop#").Width(75);
            col.Bound(o => o.JobNumber).Title("Job#").Width(75);
            col.Bound(o => o.Title).Width(200);
            col.Bound(o => o.Company).Width(200);
            col.Bound(o => o.Contact).Width(150);
            col.Bound(o => o.Industry).Width(100);
            col.Bound(o => o.SurveyJobType).Title("SurveyType").Width(100);
            col.Bound(o => o.RegulatorJobType).Title("RegType").Width(100);
            col.Bound(o => o.DueDate).Format("{0:d}").Width(100);
            col.Bound(o => o.ProjectDate).Format("{0:d}").Width(100);
            col.Bound(o => o.ProjectAmount).Title("Cost").Format("{0:c}").Width(100);
            col.Bound(o => o.EnteredBy).Width(100);
        })
        .DataBinding(d => d.Ajax().Select("_ProposalListing", "Search"))
        .ClientEvents(evt => evt.OnRowSelected("onRowSelected"))
        .Pageable(p => p.PageSize(10))
        .Resizable(r => r.Columns(true))
        .Sortable()
        .Selectable()
        .Scrollable(setting => setting.Height(500))
        .Groupable()
        .Filterable()
    )
</div>

Controller:
        [GridAction]
        public ActionResult _ProposalListing(int? proposalNumber, string title, string company) {
            var proposals = ProposalRepository.GetQuery();

            if (proposalNumber.HasValue)
                proposals = proposals.Where(p => p.ProposalNumber == proposalNumber.Value);
            if (!string.IsNullOrWhiteSpace(title))
                proposals = proposals.Where(p => p.Title.Contains(title));
            if (!string.IsNullOrWhiteSpace(company))
                proposals = proposals.Where(p => p.CompanyName.Contains(company));

            var listViewModel = ProposalRepository.GetList(proposals,
                                    j => j.Industry, j => j.SurveyType, j => j.RegulatoryType)
                                .ToList().Select(p => new ProposalSearchViewModel(p));
            return View(new GridModel<ProposalSearchViewModel>(listViewModel));
        }


This works fine for the first Page, but when I page to the next page, it loses the filter. Any way to capture the page click and send it the filter criteria and page to load i.e. something like this?

grid.bind({
    page: e.Page,
    sort: e.Sort,
    filter: {
                    proposal: proposal,
                    title: title,
                    company: company
    }
});
0
Mark
Top achievements
Rank 1
answered on 05 May 2011, 07:57 PM
I am having the issue but with a combo box. I want to use the value from the combobox when I navigate to the next page. I tried using ViewBag and ViewData but they both return null. Any ideas?
0
Atanas Korchev
Telerik team
answered on 06 May 2011, 06:45 AM
Hello Shawn,

 I don't think this forum thread discusses the same problem as yours. This forum thread is about setting the select action server side whereas you need to pass additional data to the Select method from the client-side. In that case you should use the OnDataBinding JavaScript event of the grid:

function onDataBinding(e) {
  e.data = { additionalParameterName: $("#sometextbox").val() };
}


Regards,

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
Corey Gaudin
Top achievements
Rank 1
answered on 06 May 2011, 04:32 PM
This 100% worked! Thanks Atanas, you are a life saver. May I suggest that you guys put this exact example on the MVC Examples Page to show people this. This is a pretty common scenario with pure AJAX and it would be good for others to see. Or at least expand the Client API to document what the Event Objects in the events do.


My new code layout to do Pure Ajax with Telerik Grid custom filtering, using there paging and sorting that works well:

View Script Side

        //Handle Filter Click Event
        $('#filterButton').click(function (e) {
            var grid = $('#Grid').data('tGrid');
            grid.rebind();
        });

   function onDatabinding(e) {
        var filter = getFilter();
        e.data = filter;
    }

    function getFilter() {
        var resultFilter;

            var proposal = $('#Proposal').val();
            var title = $('#ProjectTitle').val();
            var company = $('#CompanyName').val();

            resultFilter = {
                proposal: proposal,
                title: title,
                company: company
            };

        return resultFilter;
    }


View Grid:

<div id="projectList">
    @(Html.Telerik().Grid<ProposalSearchViewModel>()
        .Name("Grid")
        .DataKeys(k => k.Add(m => m.Id))
        .Columns(col => {
            col.Bound(o => o.ProposalNumber).Title("Prop#").Width(75);
            col.Bound(o => o.JobNumber).Title("Job#").Width(75);
            col.Bound(o => o.Title).Width(200);
            col.Bound(o => o.Company).Width(200);
            col.Bound(o => o.Contact).Width(150);
            col.Bound(o => o.Industry).Width(100);
            col.Bound(o => o.SurveyJobType).Title("SurveyType").Width(100);
            col.Bound(o => o.RegulatorJobType).Title("RegType").Width(100);
            col.Bound(o => o.DueDate).Format("{0:d}").Width(100);
            col.Bound(o => o.ProjectDate).Format("{0:d}").Width(100);
            col.Bound(o => o.ProjectAmount).Title("Cost").Format("{0:c}").Width(100);
            col.Bound(o => o.EnteredBy).Width(100);
        })
        .DataBinding(d => d.Ajax().Select("_ProposalListing", "Search"))
        .ClientEvents(evt => evt.OnDataBinding("onDatabinding"))
        .Pageable(p => p.PageSize(10))
        .Resizable(r => r.Columns(true))
        .Sortable()
        .Selectable()
        .Scrollable(setting => setting.Height(500))
        .Groupable()
        .Filterable()
    )
</div>

Controller:
[GridAction]
public ActionResult _ProposalListing(int? proposalNumber, string title, string company) {
var proposals = ProposalRepository.GetQuery();

if (proposalNumber.HasValue)
proposals = proposals.Where(p => p.ProposalNumber == proposalNumber.Value);
if (!string.IsNullOrWhiteSpace(title))
proposals = proposals.Where(p => p.Title.Contains(title));
if (!string.IsNullOrWhiteSpace(company))
proposals = proposals.Where(p => p.CompanyName.Contains(company));

var listViewModel = ProposalRepository.GetList(proposals,
j => j.Industry, j => j.SurveyType, j => j.RegulatoryType)
.ToList().Select(p => new ProposalSearchViewModel(p));
return View(new GridModel<ProposalSearchViewModel>(listViewModel));
}

0
Bill
Top achievements
Rank 1
answered on 03 Nov 2011, 08:24 PM
Thanks Atanas and Corey, this approach got my autocomplete to filter my ajax binding grid when the operation mode is set to server,
".OperationMode(GridOperationMode.Server)", but this doesn't work when I switch the OperationMode to .Client.

Atanas  - The code below works for .Server, but what can I do to get it to work when I set .OperationMode(GridOperationMode.Client) ?
Thanks in advance.

<script type="text/javascript">
 
    function UserAutoComplete_onChange(){
        var grid = $('#UserGrid').data('tGrid');
        //grid.filter("LoginId~eq~bill"); //tried this and doesnt work on client mode
        grid.rebind();
        var combobox = $('UserAutoComplete');
        combobox.tAutoComplete().context.close();
    }

   function onDatabinding(e) {
        e.data = getFilter();
        //e.data = { LoginId: $("#UserAutoComplete").val() }; // easy example
    }

    function getFilter() {
        var resultFilter;
            var loginid = $('#UserAutoComplete').val();
            //var param2 = $('#ProjectTitle').val();
            //var param3 = $('#CompanyName').val();
            resultFilter = {
                LoginId: loginid
                //,Param2: param2
                //,Param3: param3
            };
        return resultFilter;
    }

</script>

0
Rosen
Telerik team
answered on 04 Nov 2011, 03:04 PM
Hi Bill,

I'm afraid that setting filter expression through client-side API filter method is not currently supported when client operation mode is enabled. In order to workaround this limitation you may consider applying the filter similar to the following:

  <script type="text/javascript">
 
    function customerChange(e) {//
        var grid = $("#Grid").data("tGrid");
        var customerID = e.value;
 
        var column = grid.columnFromMember("CustomerID");
        if (column) { // setting the filter to the column in order to be persisted during paging
            column.filters = column.filters || [];
            column.filters.push({ operator: "eq", value: customerID });
        }
            //filter grid in-memory as client operation mode is used
        grid.dataSource.filter({ field: "CustomerID", operator: "eq", value: customerID });
    }
   </script>

Best wishes,
Rosen
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now
Tags
Grid
Asked by
Nebras
Top achievements
Rank 1
Answers by
Rosen
Telerik team
Nebras
Top achievements
Rank 1
Corey Gaudin
Top achievements
Rank 1
Mark
Top achievements
Rank 1
Atanas Korchev
Telerik team
Bill
Top achievements
Rank 1
Share this question
or