在ASP.NET Core MVC中应用Syncfusion EJ2服务器端分页,过滤和排序的问题

发布于 2025-02-08 20:56:14 字数 10263 浏览 2 评论 0 原文

我有7000多个记录,并使用WebApiAdapter调用API控制器并获取数据。我想应用服务器端分页,搜索和分类。例如,当我移动o第二页时,只有然后从数据库检索第二页数据。剃须刀页面的屏幕截图附加 ”在此处输入图像说明” CSHTML文件也在此处附加。

如果有人想指导我在这方面,我会很感激。谢谢

@{ ViewData["Title"] = "Product";
                MessageViewModel nullVar;
                nullVar = null; }

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    @{
    MessageViewModel message;
    if (HttpContextAccessor.HttpContext.Session.GetString("Message") != null)
    {
        message = JsonConvert.DeserializeObject<MessageViewModel>(HttpContextAccessor.HttpContext.Session.GetString("Message"));
    }
    else
    {
        message = null;
    }
}
<!-- Notification -->
@if (message != null)
{
    <div class="alert @message.CssClassName" id="msg-alert">
        <strong>@message.Title</strong>
        @message.Message
    </div>
    HttpContextAccessor.HttpContext.Session.SetString("Message", JsonConvert.SerializeObject(nullVar));
}
@*Notification when syncfusion / web api method throws exception*@
<div id="sync-msg-alert" style="display:none;">
        <strong></strong>
        <span></span>
</div>

    <!-- Main content -->
    <section class="content">
        <!-- Default box -->
        <div class="box">
            <div class="box-header with-border">
                <h3 class="box-title text-primary"><i class="fa fa-tag"></i> @ViewData["Title"]</h3>
                <div class="box-tools pull-right">
                    <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip"
                            title="Collapse">
                        <i class="fa fa-minus"></i>
                    </button>
                    <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="box-body">
                <div id="Grid"></div>
            </div>
            <!-- /.box-body -->
            <div class="box-footer">

            </div>
            <!-- /.box-footer-->
        </div>
        <!-- /.box -->
    </section>
    <!-- /.content -->
</div>
<!-- /.content-wrapper -->

@section Styles{

}

@section Scripts{

    <script type="text/javascript">

        $(document).ready(function () {
            // show the alert
            $("#msg-alert").fadeTo(5000, 500).slideUp(500, function () {
                $("#msg-alert").slideUp(500);
            });
        });

        $(function () {

            var dataManager = ej.DataManager({
                url: "/Product/GetProduct",
                adaptor: new ej.WebApiAdaptor(),
                offline: true
            });
            //This portion is used to throw error when getProduct function returns exception///
            var query = ej.Query();
            var promise = dataManager.executeQuery(query);
            
            promise.fail(function (e) {
            $("#sync-msg-alert").css("display", "block");
            $("#sync-msg-alert").addClass("alert alert-danger");
            $("#sync-msg-alert > strong").html("Error!");
            $("#sync-msg-alert > span").html("Unable to load the list due to some error");
            // show the alert
            $("#sync-msg-alert").fadeTo(5000, 500).slideUp(500, function () {
                $("#sync-msg-alert").slideUp(500);
            });
            });
            ////////////////////////////////////////////////////////////////////////////////////
            var dataManagerUnitOfMeasure = ej.DataManager({
                url: "/api/UnitOfMeasure",
                adaptor: new ej.WebApiAdaptor()
            });

            var dataManagerBranch = ej.DataManager({
                url: "/api/Branch",
                adaptor: new ej.WebApiAdaptor()
            });
            var dataManagerDepartment = ej.DataManager({
                url: "/api/Department",
                adaptor: new ej.WebApiAdaptor()
            });

            var dataManagerCurrency = ej.DataManager({
                url: "/api/Currency",
                adaptor: new ej.WebApiAdaptor()
            });

            dataManager.ready.done(function (e) {
                $("#Grid").ejGrid({
                    dataSource: ej.DataManager({
                        json: e.result,
                        adaptor: new ej.remoteSaveAdaptor(),
                        removeUrl: "/Product/Remove",
                    }),
                    toolbarSettings: {
                        showToolbar: true,
                        toolbarItems: ["add", "delete", "update", "cancel", "search", "printGrid"]
                    },
                    toolbarClick: toolbarClickHandler,
                    editSettings: {
                        allowEditing: false,
                        allowAdding: true,
                        allowDeleting: true,
                        showDeleteConfirmDialog: true
                    },
                    isResponsive: true,
                    enableResponsiveRow: true,
                    allowSorting: true,
                    allowSearching: true,
                    allowFiltering: true,
                    filterSettings: {
                        filterType: "excel",
                        maxFilterChoices: 100,
                        enableCaseSensitivity: false
                    },
                    allowPaging: true,
                    pageSettings: { pageSize: 10, printMode: ej.Grid.PrintMode.CurrentPage },
                    columns: [
                        { field: "ProductId", headerText: 'Product Id', isPrimaryKey: true, isIdentity: true, visible: false },
                        { field: "Configuration", headerText: 'Configuration', validationRules: { required: true } },
                        { field: "Barcode", headerText: 'Barcode', },
                        { field: "DefaultBuyingPrice", headerText: 'Buying Price', editType: "numericedit", format: "{0:n2}" },
                        { field: "DefaultSellingPrice", headerText: 'Selling Price', editType: "numericedit", format: "{0:n2}" },
                        { field: "BranchId", headerText: 'Branch', foreignKeyField: "BranchId", foreignKeyValue: "BranchName", dataSource: dataManagerBranch },
                        { field: "DepartmentId", headerText: 'Department', foreignKeyField: "DepartmentId", foreignKeyValue: "DepartmentName", dataSource: dataManagerDepartment },
                        {
                            headerText: "Action",
                            commands: [
                                { 
                                    type: ej.Grid.UnboundType.Edit, buttonOptions: { contentType: "imageonly", prefixIcon: "e-icon e-edit", click: "editClick" }
                                },
                                {
                                    type: ej.Grid.UnboundType.Delete, buttonOptions: { contentType: "imageonly", prefixIcon: "e-icon e-delete" }
                                }
                            ],
                            isUnbound: true
                        }
                    ],
                    actionComplete: "complete",
                    recordDoubleClick: "recordDoubleClickFunc",
                    actionFailure: "actionFailure"
                });
            });


        });
        function actionFailure(args) { 
        if (args.requestType == 'begindelete' || args.requestType == 'delete') {
                $("#sync-msg-alert").css("display", "block");
                $("#sync-msg-alert").addClass("alert alert-danger");
                $("#sync-msg-alert > strong").html("Error!");
                $("#sync-msg-alert > span").html("Cannot delete record due to some error");
                // show the alert
                $("#sync-msg-alert").fadeTo(5000, 500).slideUp(500, function () {
                    $("#sync-msg-alert").slideUp(500);
                });
            }
        }
        function toolbarClickHandler(args) {
            if (args.itemName == "Add") {
                $("#Grid").ejGrid({
                    editSettings: {
                        allowAdding: false
                    },
                });
                window.location.href = '/Product/Add';
            }
            else {
                $("#Grid").ejGrid({
                    editSettings: {
                        allowAdding: true
                    },
                });
            }
        }
        function editClick(args) {
            //args has button related properties here so can't retreive other columns
            /*getting grid*/
            var gridObj = $("#Grid").data("ejGrid");
            //get selected row's ProductId
            var productId = gridObj.getSelectedRecords()[0].ProductId;

            window.location.href = '/Product/Update/' + productId;
        }
        function recordDoubleClickFunc(args) {
            window.location.href = '/Product/Update/' + args.rowData.ProductId;
        }
        function complete(args) {
            if (args.requestType == 'begindelete' || args.requestType == 'delete') {
                $("#sync-msg-alert").css("display", "block");
                $("#sync-msg-alert").addClass("alert alert-success");
                $("#sync-msg-alert > strong").html("Success!");
                $("#sync-msg-alert > span").html("Record Deleted Successfully");
                // show the alert
                $("#sync-msg-alert").fadeTo(5000, 500).slideUp(500, function () {
                    $("#sync-msg-alert").slideUp(500);
                });
            }
        }
</script>
}

I have 7000+ Records and using WebAPIAdapter to call the API controller and get the data. I want to apply server-side paging, searching and sorting. For example, When I move o second page, only then it retrieve second page data from the DB. The screenshot of razor Page is attached enter image description here
The cshtml file is also attached here.

I would be grateful if anyone would like to guide me in this regard. Thanks

@{ ViewData["Title"] = "Product";
                MessageViewModel nullVar;
                nullVar = null; }

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    @{
    MessageViewModel message;
    if (HttpContextAccessor.HttpContext.Session.GetString("Message") != null)
    {
        message = JsonConvert.DeserializeObject<MessageViewModel>(HttpContextAccessor.HttpContext.Session.GetString("Message"));
    }
    else
    {
        message = null;
    }
}
<!-- Notification -->
@if (message != null)
{
    <div class="alert @message.CssClassName" id="msg-alert">
        <strong>@message.Title</strong>
        @message.Message
    </div>
    HttpContextAccessor.HttpContext.Session.SetString("Message", JsonConvert.SerializeObject(nullVar));
}
@*Notification when syncfusion / web api method throws exception*@
<div id="sync-msg-alert" style="display:none;">
        <strong></strong>
        <span></span>
</div>

    <!-- Main content -->
    <section class="content">
        <!-- Default box -->
        <div class="box">
            <div class="box-header with-border">
                <h3 class="box-title text-primary"><i class="fa fa-tag"></i> @ViewData["Title"]</h3>
                <div class="box-tools pull-right">
                    <button type="button" class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip"
                            title="Collapse">
                        <i class="fa fa-minus"></i>
                    </button>
                    <button type="button" class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove">
                        <i class="fa fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="box-body">
                <div id="Grid"></div>
            </div>
            <!-- /.box-body -->
            <div class="box-footer">

            </div>
            <!-- /.box-footer-->
        </div>
        <!-- /.box -->
    </section>
    <!-- /.content -->
</div>
<!-- /.content-wrapper -->

@section Styles{

}

@section Scripts{

    <script type="text/javascript">

        $(document).ready(function () {
            // show the alert
            $("#msg-alert").fadeTo(5000, 500).slideUp(500, function () {
                $("#msg-alert").slideUp(500);
            });
        });

        $(function () {

            var dataManager = ej.DataManager({
                url: "/Product/GetProduct",
                adaptor: new ej.WebApiAdaptor(),
                offline: true
            });
            //This portion is used to throw error when getProduct function returns exception///
            var query = ej.Query();
            var promise = dataManager.executeQuery(query);
            
            promise.fail(function (e) {
            $("#sync-msg-alert").css("display", "block");
            $("#sync-msg-alert").addClass("alert alert-danger");
            $("#sync-msg-alert > strong").html("Error!");
            $("#sync-msg-alert > span").html("Unable to load the list due to some error");
            // show the alert
            $("#sync-msg-alert").fadeTo(5000, 500).slideUp(500, function () {
                $("#sync-msg-alert").slideUp(500);
            });
            });
            ////////////////////////////////////////////////////////////////////////////////////
            var dataManagerUnitOfMeasure = ej.DataManager({
                url: "/api/UnitOfMeasure",
                adaptor: new ej.WebApiAdaptor()
            });

            var dataManagerBranch = ej.DataManager({
                url: "/api/Branch",
                adaptor: new ej.WebApiAdaptor()
            });
            var dataManagerDepartment = ej.DataManager({
                url: "/api/Department",
                adaptor: new ej.WebApiAdaptor()
            });

            var dataManagerCurrency = ej.DataManager({
                url: "/api/Currency",
                adaptor: new ej.WebApiAdaptor()
            });

            dataManager.ready.done(function (e) {
                $("#Grid").ejGrid({
                    dataSource: ej.DataManager({
                        json: e.result,
                        adaptor: new ej.remoteSaveAdaptor(),
                        removeUrl: "/Product/Remove",
                    }),
                    toolbarSettings: {
                        showToolbar: true,
                        toolbarItems: ["add", "delete", "update", "cancel", "search", "printGrid"]
                    },
                    toolbarClick: toolbarClickHandler,
                    editSettings: {
                        allowEditing: false,
                        allowAdding: true,
                        allowDeleting: true,
                        showDeleteConfirmDialog: true
                    },
                    isResponsive: true,
                    enableResponsiveRow: true,
                    allowSorting: true,
                    allowSearching: true,
                    allowFiltering: true,
                    filterSettings: {
                        filterType: "excel",
                        maxFilterChoices: 100,
                        enableCaseSensitivity: false
                    },
                    allowPaging: true,
                    pageSettings: { pageSize: 10, printMode: ej.Grid.PrintMode.CurrentPage },
                    columns: [
                        { field: "ProductId", headerText: 'Product Id', isPrimaryKey: true, isIdentity: true, visible: false },
                        { field: "Configuration", headerText: 'Configuration', validationRules: { required: true } },
                        { field: "Barcode", headerText: 'Barcode', },
                        { field: "DefaultBuyingPrice", headerText: 'Buying Price', editType: "numericedit", format: "{0:n2}" },
                        { field: "DefaultSellingPrice", headerText: 'Selling Price', editType: "numericedit", format: "{0:n2}" },
                        { field: "BranchId", headerText: 'Branch', foreignKeyField: "BranchId", foreignKeyValue: "BranchName", dataSource: dataManagerBranch },
                        { field: "DepartmentId", headerText: 'Department', foreignKeyField: "DepartmentId", foreignKeyValue: "DepartmentName", dataSource: dataManagerDepartment },
                        {
                            headerText: "Action",
                            commands: [
                                { 
                                    type: ej.Grid.UnboundType.Edit, buttonOptions: { contentType: "imageonly", prefixIcon: "e-icon e-edit", click: "editClick" }
                                },
                                {
                                    type: ej.Grid.UnboundType.Delete, buttonOptions: { contentType: "imageonly", prefixIcon: "e-icon e-delete" }
                                }
                            ],
                            isUnbound: true
                        }
                    ],
                    actionComplete: "complete",
                    recordDoubleClick: "recordDoubleClickFunc",
                    actionFailure: "actionFailure"
                });
            });


        });
        function actionFailure(args) { 
        if (args.requestType == 'begindelete' || args.requestType == 'delete') {
                $("#sync-msg-alert").css("display", "block");
                $("#sync-msg-alert").addClass("alert alert-danger");
                $("#sync-msg-alert > strong").html("Error!");
                $("#sync-msg-alert > span").html("Cannot delete record due to some error");
                // show the alert
                $("#sync-msg-alert").fadeTo(5000, 500).slideUp(500, function () {
                    $("#sync-msg-alert").slideUp(500);
                });
            }
        }
        function toolbarClickHandler(args) {
            if (args.itemName == "Add") {
                $("#Grid").ejGrid({
                    editSettings: {
                        allowAdding: false
                    },
                });
                window.location.href = '/Product/Add';
            }
            else {
                $("#Grid").ejGrid({
                    editSettings: {
                        allowAdding: true
                    },
                });
            }
        }
        function editClick(args) {
            //args has button related properties here so can't retreive other columns
            /*getting grid*/
            var gridObj = $("#Grid").data("ejGrid");
            //get selected row's ProductId
            var productId = gridObj.getSelectedRecords()[0].ProductId;

            window.location.href = '/Product/Update/' + productId;
        }
        function recordDoubleClickFunc(args) {
            window.location.href = '/Product/Update/' + args.rowData.ProductId;
        }
        function complete(args) {
            if (args.requestType == 'begindelete' || args.requestType == 'delete') {
                $("#sync-msg-alert").css("display", "block");
                $("#sync-msg-alert").addClass("alert alert-success");
                $("#sync-msg-alert > strong").html("Success!");
                $("#sync-msg-alert > span").html("Record Deleted Successfully");
                // show the alert
                $("#sync-msg-alert").fadeTo(5000, 500).slideUp(500, function () {
                    $("#sync-msg-alert").slideUp(500);
                });
            }
        }
</script>
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

长伴 2025-02-15 20:56:14

我们为您的需求创建了以下示例。在此样本中,我们使用了带有OdataQueryOptions的WEP API适配器。我们可以使用ODATAQUERYOPTIONS参数执行服务器端操作,例如过滤,分页,分类和分组。请参阅示例和代码示例,

示例:

代码示例示例:

@(html.ej()

          .Datasource(ds => ds.URL("/api/Orders").Adaptor(AdaptorType.WebApiAdaptor)) 

          .AllowPaging() 

          .AllowGrouping() 

          .AllowSorting() 

          .AllowFiltering() 

          .FilterSettings(f => f.FilterType(FilterType.Excel)) 

          .PageSettings(page => { page.PageSize(8); }) 

           

           . . .  

          .Columns(col => 

          { 

                . . .    

          }) 

) 

    public PageResult<OrdersView> Get(ODataQueryOptions opts) 

    { 

        var emp = db.OrdersViews.Take(50).AsQueryable(); 

        var count = emp.Count(); 



        if (opts.OrderBy != null) 

            emp = opts.OrderBy.ApplyTo(emp);  //perform sort 

        if (opts.Filter != null) 

            emp = opts.Filter.ApplyTo(emp, new ODataQuerySettings()).Cast<OrdersView>();  //perform filter 

        if (opts.InlineCount != null) 

            count = emp.ToList().Count; 

        if (opts.Skip != null) 

            emp = opts.Skip.ApplyTo(emp, new ODataQuerySettings());  //perform skip 

        if (opts.Top != null) 

            emp = opts.Top.ApplyTo(emp, new ODataQuerySettings());  //perform take 





        return new PageResult<OrdersView>(emp, null, count); 



    } 

We have created a following sample for your requirement. In this sample we have used wep Api adaptor with ODataQueryOptions. We can perform server side operations such as filtering, paging , sorting and grouping by using ODataQueryOptions parameter. Please refer to the sample and code example,

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/WebApiSample-274345982

Code example:

@(Html.EJ().Grid("Grid")

          .Datasource(ds => ds.URL("/api/Orders").Adaptor(AdaptorType.WebApiAdaptor)) 

          .AllowPaging() 

          .AllowGrouping() 

          .AllowSorting() 

          .AllowFiltering() 

          .FilterSettings(f => f.FilterType(FilterType.Excel)) 

          .PageSettings(page => { page.PageSize(8); }) 

           

           . . .  

          .Columns(col => 

          { 

                . . .    

          }) 

) 

NorthwindDataContext db = new NorthwindDataContext();

    public PageResult<OrdersView> Get(ODataQueryOptions opts) 

    { 

        var emp = db.OrdersViews.Take(50).AsQueryable(); 

        var count = emp.Count(); 



        if (opts.OrderBy != null) 

            emp = opts.OrderBy.ApplyTo(emp);  //perform sort 

        if (opts.Filter != null) 

            emp = opts.Filter.ApplyTo(emp, new ODataQuerySettings()).Cast<OrdersView>();  //perform filter 

        if (opts.InlineCount != null) 

            count = emp.ToList().Count; 

        if (opts.Skip != null) 

            emp = opts.Skip.ApplyTo(emp, new ODataQuerySettings());  //perform skip 

        if (opts.Top != null) 

            emp = opts.Top.ApplyTo(emp, new ODataQuerySettings());  //perform take 





        return new PageResult<OrdersView>(emp, null, count); 



    } 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文