Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

ModelExtensions.cs

using Nop.Core;

namespace Nop.Web.Framework.Models.Extensions;

/// 
/// Represents model extensions
/// 
public static class ModelExtensions
{
    /// 
    /// Convert list to paged list according to paging request
    /// 
    /// Object type
    /// List of objects
    /// Paging request model
    /// Paged list
    public static IPagedList ToPagedList(this IList list, IPagingRequestModel pagingRequestModel)
    {
        return new PagedList(list, pagingRequestModel.Page - 1, pagingRequestModel.PageSize);
    }

    /// 
    /// Convert async-enumerable sequence to paged list according to paging request
    /// 
    /// Object type
    /// Async-enumerable sequence of objects
    /// Paging request model
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the paged list
    /// 
    public static async Task> ToPagedListAsync(this IAsyncEnumerable collection, IPagingRequestModel pagingRequestModel)
    {
        var list = await collection.ToListAsync();
        return list.ToPagedList(pagingRequestModel);
    }

    /// 
    /// Prepare passed list model to display in a grid
    /// 
    /// List model type
    /// Model type
    /// Object type
    /// List model
    /// Search model
    /// Paged list of objects
    /// Function to populate model data
    /// List model
    public static TListModel PrepareToGrid(this TListModel listModel,
        BaseSearchModel searchModel, IPagedList objectList, Func> dataFillFunction)
        where TListModel : BasePagedListModel
        where TModel : BaseNopModel
    {
        ArgumentNullException.ThrowIfNull(listModel);

        listModel.Data = dataFillFunction?.Invoke();
        listModel.Draw = searchModel?.Draw;
        listModel.RecordsTotal = objectList?.TotalCount ?? 0;
        listModel.RecordsFiltered = objectList?.TotalCount ?? 0;

        return listModel;
    }

    /// 
    /// Prepare passed list model to display in a grid
    /// 
    /// List model type
    /// Model type
    /// Object type
    /// List model
    /// Search model
    /// Paged list of objects
    /// Function to populate model data
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the list model
    /// 
    public static async Task PrepareToGridAsync(this TListModel listModel,
        BaseSearchModel searchModel, IPagedList objectList, Func> dataFillFunction)
        where TListModel : BasePagedListModel
        where TModel : BaseNopModel
    {
        ArgumentNullException.ThrowIfNull(listModel);

        listModel.Data = await (dataFillFunction?.Invoke()).ToListAsync();
        listModel.Draw = searchModel?.Draw;
        listModel.RecordsTotal = objectList?.TotalCount ?? 0;
        listModel.RecordsFiltered = objectList?.TotalCount ?? 0;

        return listModel;
    }
}