问题
I have a Telerik MVC Grid using ajax to get data and I want to control when it will be loaded.
Here is the code in my view:
@(Html.Telerik().Grid<ViewModels.Reports.UserActionLoggingDetailViewModel>()
.Name("UserActionLoggingFollowedGrid")
.DataBinding(dataBinding => dataBinding.Ajax().Select("SelectUserActionLogging", "Report", new { userTeamId = Model.UserTeamId, startDate = Model.StartDate, endDate = Model.EndDate }).OperationMode(GridOperationMode.Client))
.Columns(columns =>
{
columns.Bound(x => x.FullName).Hidden();
columns.Bound(x => x.ActionName);
columns.Bound(x => x.ActionCount);
})
.Pageable(page => page.PageSize(20))
.Sortable()
.Groupable(grouping => grouping.Groups(groups => groups.Add(c => c.FullName)).Visible(false))
.Filterable()
.Localizable("fr-FR")
.HtmlAttributes(new { @class = "grid-style static-grid-style" })
.ClientEvents(e => e.OnError("Grid_onServerError").OnDataBinding("Grid_onDataBinding").OnDataBound("Grid_onDataBound"))
)
By default, this code works correctly. When the page is loaded, the grid send automatically a post request to the server for the specified action and load itself with the returned datas.
What I want is the same grid with the same behavior but without loading data when the page is loaded; I want the grid to be loaded when the user click a button or any other actions.
I found some interesting posts indicating how to manually refresh the grid but no one specified how to prevent the initial bind of the grid.
回答1:
This little piece works for me. Add a data binding client event (which you already have, apparently):
.ClientEvents(events => events
.OnDataBinding("preventAjaxSelectOnPageLoad"))
Then create add this javascript:
<script type="text/javascript">
var gridsToBind = [];
function preventAjaxSelectOnPageLoad(e)
{
if ($.inArray(e.target.id, gridsToBind) == -1)
{
e.preventDefault();
gridsToBind.push(e.target.id);
}
}
</script>
Basically, you create an array to keep track of the grids that need to bind. When the page loads, the array will be empty - at that point, it cancels the data binding event and adds the grid to the array. Then the next time ajaxRequest() is called, the grid exists in the array and can be bound normally.
回答2:
I think that you can add a handler for the DataBinding or DataBound events for the grid, and check if it is the first load of the page there. If so, use e.preventDefault() in order to avoid to make the call to the server.
Other option could be removing the ajax binding from the Grid declaration and do it by yourself using the dataBind method
来源:https://stackoverflow.com/questions/11680081/telerik-mvc-grid-ajax-with-manually-binding