Giter VIP home page Giter VIP logo

aspnetcore's Introduction

ASP.NET Core Utility

This solution add some useful features for ASP.NET Core projects. All projects in this solution are designed for cross-platform "netstandard" and triditional .NET Full "net" frameworks.

This solution contains the following aspects:

  • Tag Helpers
  • Middlewares
  • Utilities

Current Project List

This section lists all projects in the repo. The list will always update in time.

External Cookie Services

Nuget Package Name: Sakura.AspNetCore.Authentication.ExternalCookie

ASP.NET Core Identity Service (Microsoft.AspNet.Identity package) already added support for external cookie services, which is required for 3rd application authentication scheme (e.g. Microsoft of Fackbook account). You may use AddIdentity and UseIdentity method to enable external cookie services. However, in sometimes you may wish to enable external services indivindually without full ASP.NET Identity Service enabled. This project seperates the external cookie services from ASP.NET Identity Services, and may be used in more complex authentication scenes.

The major feature of this project contains:

  • Configure ASP.NET Core Application to support ApplicationCookie and ExternalCookie services (provides extension methods can be used in ConfigureServices method of ASP.NET Startup class)
  • Provide ExternalSignInManager service to simpify external cookie ticket management.

ASP.NET Core MVC TagHelper Extension Library

Nuget Package Name: Sakura.AspNetCore.Mvc.TagHelpers

Provide new tag helpers in order to simplify MVC code writing. For more details, please visit the Tag Helper Demo page.

ASP.NET TempData Extension Package

Nuget Package Name: Sakura.AspNetCore.Mvc.TempDataExtensions

This project provides the EnhancedSessionStateTempDataProvider service provider, with can replace the original SessionBasedTempDataProvider, in order to enhance the type compatibility for session data. The original TempData provider can only work with primitive types, arrays, and one-level plain-objects, objects with complex properties are not supported. The EnhancedSessionStateTempDataProvider can successfully work with most data objects with arbitray level structures.

Internally, it uses certain serializer techinque to convert complex data into string value, and store it together with its type full name. When application loading its content, it will deserialize the string to recover the object data structure. The default implmementation uses JsonObjectSerializer, and you may also replace it with your own implementation if necessary.

ASP.NET Core MVC Messages Package

Nuget Package Name: Sakura.AspNetCore.Mvc.Messages

This project add the feature of common operation message response in web applications, as well as tag helpers to simplify message presentations. The detailed features includes:

  • OperationMessage definitions and different OperationMessageLevel enum items.
  • IOperationMessageAccessor service, which can be inject in both views and controllers to access operation message data.
  • MessageTagHelper helper class, and you may use asp-message-list attribute on div element to generate message list UI, with various styles and additional layout options can be specified.
  • IOperationMessageHtmlGenerator service, wich is used internally for generating message list UI, and default bootstrap style generator are built-in implemented.

*NOTE: To use this package, your ITempDataProvider implementation must have the ability to store and load ICollection<OperationMessage> instance. Defaultly, the ASP.NET5 SessionStateTempDataProvider cannot support data operation of complex objects. You may change into another ITempDataProvider implementation, or just use EnhancedSessionStateTempDataProvider in the ASP.NET TempData Extension Package project.

ASP.NET Core PagedList Packages

Nuget Package Name:

  • Sakura.AspNetCore.PagedList
  • Sakura.AspNetCore.PagedList.Async
  • Sakura.AspNetCore.Mvc.PagedList

The Sakura.AspNetCore.PagedList package provides the IPagedList core interface to represent as a data page for a large data source. Some extension methods are also provided to generate instance from any IEnumerable<T> or IQueryable<T> data sources.

The Sakura.AspNetCore.PagedList.Async package helpes you to generate IPagedList using async extension method (ToArrayAsync, etc.) defined in Microsoft.EntityFrameworkCore package.

The Sakura.AspNetCore.Mvc.PagedList allows you to use <pager> tag in your MVC view page to generate a full featured pager structure.

For detailed usage, please visit the Demo page. Notice: this package has been updated to version 2 (the recommended version). For usage of version 1, please visit the Version 1 Demo page.

ASP.NET ActionResult Extensions Package

Nuget Package Name: Sakura.AspNetCore.Mvc.ActionResultExceptionExtensions

In MVC Projects, you need to return a instance of IActionResult to finish the action pipeline, this design made it difficult to add common helper functions to make argument or permission checking and then report a specified status code directly to end user. This library allows you to terminate action executing pipeline directly with a specified result through the standard exception handling system.

In order to enable this feature, all you need is adding an EnableActionResultException attribute on a controller or action, and then you can throw an ActionResultExceptioninstance to terminate a action executing pipeline directly and provide the final action result. If you need to enable this feature globally, you can use EnableActionResultExceptionFilter extension method on MvcOptions parameter when you add the MVC middleware.

ASP.NET Core MVC Dyanmic Localizer Package

Nuget Package Name: Sakura.AspNetCore.DynamicLocalizer

ASP.NET Core 1.0 introduced a new localization design model, which allow developers to access localized resources using IStringLocalizer, IHtmlLocalizer or IViewLocalizer service instances. In order to keep compatibilty and reduce the time cost for switching the developing time single language website into production multiple language implementation, ASP.NET Core team suggests developers to use string context itself as the language resource keys. e.g. the following code

@ViewLocalizer["Hello World"]

while output the key string "hello world" when there's no resource files defined or the resource for current culture is unavialable.

Although this design reduces the time cost of enabling multiple language support, lots of developers may still build the website with multiple language support from the beginning. The above manner may not be optimized for these scenes, since under such circumstance, developers may choose to use identifier-like word as keys for long messages, e.g. the final code in the CSHTML file maybe:

@ViewLocalizer["HelloWorldMessage"]

However, actually developers may love the following code style much more:

@ViewLocalizer.HelloWorldMessage

The above code style looks with much more object-oriented code style, and may also take a lot of editing and compiling time benefits such as identifier checking, searching and intellisence. This behaviour is also favorite for old-time .NET Resource Manager based localizaable applications, in which each resources is named with an identifier and the resource file generators will help you to generate classes for resources, and developers may use strong named propreties to access resources.

The Sakura.AspNetCore.DynamicLocalizer package now provides a simplified simulation for object-oreinted resource accessing style using .NET dynamic objects. For a simple usage, you may install this package and add the necessary services on startup using the following code:

public void ConfigureServices(IServiceCollection services)
{
  // other service configurations here
  
  // Note: the following base services are necessary and must be also added manually in your startup code
  services.AddLocalization();
  services.AddMvc().AddViewLocalization();
  
  // add core services used for dynamic localizer
  services.AddDynamicLocalizer();
}

And now in MVC views, you may using dyanmic object as localization services, the basic usage is shown in the following code:

@inject Sakura.AspNetCore.IDynamicViewLocalizer ViewLocalizer
@inject Sakura.AspNetCore.IDynamicHtmlLocalizer<MyResource> MyResourceLocalizer

<p>@ViewLocalizer.Html.WelcomeMessage</p>
<p>@ViewLocalizer.Html.UserNameFormat(ViewBag.UserName)</p>

<p>@MyResourceLocalizer.Html.ImportantTip<Hello>

More specifically, the relationship between original localizers and dynamic localizers are shown as bellow:

Original Dynamic
IViewLocalizer IDyanmicViewLocalizer
IHtmlLocalizer<T> IDynamicHtmlLocalizer<T>
IStringLocalizer<T> IDynamicStringLocalizer<T>

The following tables showes the supported invocation syntax for dynamic localizers (words in braces are identfier placeholders):

Syntax Equivelant Orignal Syntax Notes
localizer.Html.{Key} localizer.GetHtml("{Key}")] This method is not available in IStringLocalizer
localizer.Html.{Key}({Value1}, {Value2}) localizer.GetHtml("{Key}", Value1, Value2)] This method is not available in IStringLocalizer
localizer.Text.{Key} localizer.GetString("{Key}") Allowed in all localizers
localizer.Text.{Key}({Value1}, {Value2}) localizer.GetString("{Key}", Value1, Value2)] Allowed in all localizers

Note: The behaviour default index-style syntax (e.g. localizer["Key", Value1, Value2]) depends on the type of the localizer. For IViewLocalizer and IHtmlLocalizer, it is equivelant to GetHtml, while for IStringLocalizer, it's equivelant to GetString.

For compatbility reason, the dynamic localizer also support the index style syntax, which will generate the same effect for the new syntax, e.g. localizer.Html["{Key}", Value1, Value2] are equivelant to localizer.Html.Key(Value1, Value2).

ASP.NET Entity Framework Core FromSql Extension Package

Nuget Package Name: Sakura.EntityFrameworkCore.FromSqlExtensions

In Entity Framework Core 2.1, the concept of the new QueryType is introduced, which allows developers to mapping non-table-based query results (e.g. data comes from a database view or a stored procedure) to CLR types. However, in order to use query types, you must first include it in your model. This restriction will cause you to take a lot of unnecessary work when you want to executing a raw SQL statement directly.

More specifically, let's see an example. You want to query some data using a stored procedure named "GetTopStudents" from your database, you know the procedure will produce the top 10 students with highest scores along with their name, and then you may define a query type as well as the following executing codes:

public class TopStudentInfo
{
  public string Name { get; set; }
  public int Score { get; set; }
}

// The following code is used to extract the top student infomation.
var result = MyDbContext.Query<TopStudentInfo>().FromSql("EXEC [GetTopStudents]");

However, when you try to execute the code above, Entity Framework Core will tell you that the TopStudentInfo is not included in the model. In order to fix this exception, you must first include it just like:

public class StudentDbContext : DbContext
{
  public virtual DbQuery<TopStudentInfo> TopStudents { get; set; }
}

And then you can get the result using either

MyDbContext.Query<TopStudentInfo>().FromSql("EXEC [GetTopStudents]")

or

MyDbContext.TopStudents.FromSql("EXEC [GetTopStudents]")

The reason why EF requires you to include the query type is to support a chained-query just like from i in MyDbContext.TopStudents select i. Under such circumstance, the query type must be included and mapped with either ToView or ToQuery to declare its original data source. However, if you just want to take usage of the FromSql method, the mapping step will be reduntant, but you still need to define the query type in your DbContext class.

Considering that you may executing serveral different raw SQL queries or stored procedures in your project. For each of them, you must include the query type into your model individually and this requirement will be a quite boring work. Now the Sakura.EntityFrameworkCore.FromSqlExtensions package provides extension methods for including query types and executing raw SQL statements directly, now you may using the following code:

var result = MyDbContext.FromSql<TopStudents>("EXEC [GetTopStudents]");

to get the result without explicitly defining a context-level DbQuery instance.

Note: Internally, this extension method will register the query type into the model globally when you call it if it not exists before, and thus after you call this method sereval times with different types, there will be a huge number of query types added in your model. It may seems to be a side-effect (although adding a new query type actually does not generate performance burden for EF Core), while is problem is caused by the internal design of the EF Core and currently it is not possible to implement query-level type registrations.


Contribution and Discussion

You are welcome to add issues and advices, if you want to contribute to the project, please fell free to make pull requests.

aspnetcore's People

Contributors

dependabot[bot] avatar sgjsakura avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aspnetcore's Issues

Ajax support

Hi,

Thank you for the efforts,
I think it is better if you added ajax support to the pager in pagedlist tag helper, not having that is a big turn off and we need to do a workaround to support ajax.

You can add the data-ajax-*

Thanks

Pager is appending extra links after click

I am using the pager for 67 pages. The pager initially displays with 1 2 3 ... 65 66 67. When I click on the page 3 link, the pager is now 1 2 3 4 5 ... 65 66 67. If I then click on page 65 link, the pager is 1 2 3 ... 63 64 65 66 67.

I know there must be something simple that I am missing but I have been racking my brain for the last day and half. Any help would be greatly appreciated.

Custom paging parameters cannot be obtained

page

global
public void ConfigureServices(IServiceCollection services) { services.AddBootstrapPagerGenerator(options => { // Use default pager options. options.ConfigureDefault(); }); }
action
`public IActionResult DataPager(string tagname,int page)
{

} `
The tagname does not get the parameter value
I don't know if I have any other configuration wrong?
Thank you for your reply.

Ajax pager help

Hey mate, having a bit of an issue using the ajax pagination.
I am trying to do simple table pagination, and I've got it working using direct links, but ajax would be preferable.
I've used the library suggested in the demo and enabled ajax navigation on the pager. If I leave it at that, obviously clicking the pagination buttons results in nothing happening.
I then read issue #8 and experimented with what you suggested there. Upon adding the method and update attributes it kind of worked, however it inserts an updated version of the entire page body it into the specified div. How do I get it to only update the table?
I don't have much experience with ajax, so i'm sure this is relatively simple to fix, so a prod in the right direction would be appreciated!

this is my current pager code:

<pager source="Model.Result" item-default-link='PagerItemLinkGenerators.QueryName("resultpage")' setting-link-attr-data-ajax="true" setting-link-attr-data-ajax-method="GET" setting-link-attr-data-ajax-load="#results" />

And the table in my view is something like this:

<table id="results" class="table">
            <tr>
                <th>
                    headers
                </th>                
            </tr>
            @foreach (var item in Model.Result)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.ResultExample)
                    </td>
                </tr>
            }
</table>

An item with the same key has already been added. Key: Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadata

I Create a new solution with VS 2017. My solution contain the following project

1- Application.models (Class Library DotNetCore)
Reference : Sakura.AspNetCore.Mvc.PagedList (2.0.12) AND Sakura.AspNetCore.PagedList
My Model is:
using Sakura.AspNetCore;
using System;

namespace Hospea.Model
{
public class DetailModel
{
public int DetailId { get; set; }
public string DetailNumber { get; set; }
}

public class SearchModel
{

    public string CustomerName { get; set; }
    public int? Page { get; set; }
    public string SortColumn { get; set; }
    public string Direction { get; set; }

    public string SortExpression
    {
        get
        {
            return string.IsNullOrEmpty(SortColumn) ? string.Empty
                       : string.Format("{0} {1}", SortColumn, Direction);
        }
    }
    public string SearchButton { get; set; }

    public IPagedList<DetailModel> Details { get; set; }
}

}

2- A second project Application.DataAccess (Class Library DotNetCore)
reference to : Application.Model

contain a function that return IEnumerable

3- Application.Web (Application Web Asp .Net Core (.netCore)
Reference Application.DataAccess
Contain a controller with action :
public IActionResult Index(SearchModel model)
{
return View(model);
}

When I run my application and try to run my action, i have the error

An item with the same key has already been added. Key: Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadata

An item with the same key has already been added

Getting error message

ArgumentException: An item with the same key has already been added. Key: Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadata

HAPPENS WHEN
I have a a typical forum structure, and hereby have threads. I'm using your pager to only show 20 comments per thread per page. Imagine being on the first page (showing 20 comments for the thread). In the bottom I have a textarea allowing logged in users to add a new comment to the thread. Whenever I press "Add comment" and submit my form, I receive this error.

SPECS
Core version: 1.0.0
Sakura.AspNetCore.PagedList version: 2.0.1
Sakura.AspNetCore.Mvc.PagedList version: 2.0.9

If you need further information please tell me.

Null source in version 3.0.1

Hi,
I have a problem when I upgraded my "Sakura.AspNetCore.Mvc.PagedList" package to version 3.0.1:

InvalidOperationException: The specified paging source came from the 'source' cannot be null
Sakura.AspNetCore.Mvc.TagHelpers.PagerTagHelper.GetPagingInfoFromSource(out int currentPage, out int totalPage)
Sakura.AspNetCore.Mvc.TagHelpers.PagerTagHelper.GetPagingInfo(TagHelperContext context, out int currentPage, out int totalPage)
Sakura.AspNetCore.Mvc.TagHelpers.PagerTagHelper.Process(TagHelperContext context, TagHelperOutput output)

I didn't have this problem in version 3.0.0 but in that version I had to add total-page and current-page to the tag helper manually as follow:
<pager total-page="@Model.TotalPage" current-page="@Model.PageIndex" />

Thanks,

ToPagedList method is not available

I was trying to call ToPagedList() on a List object. But it seems the method is not available in the Sakura.AspNetCore namespace. In resharper is shows in red color. Can some one guide me to solve the matter ?

Thanks.

PagerItemLinkGenerators not in the current context

Hello,
I need to rewrite the pager link as I am using partial views and it doesn't point to the correct module. I read in the tutorial that I would need to use PagerItemLinkGenerators such as
<pager source="Model.StaffResults" item-default-link='PagerItemLinkGenerators.Format...
but i get a "The name PagerItemLinkGenerators does not exist in the current context".

I have added the following in the appsettings.json:

,
  "Pager": {
    "ExpandPageItemsForCurrentPage": 2,
    "PageItemsForEnding": 3,
    "Layout": "Default",
    "AdditionalSettings": {
      "my-setting-one": "1"
    },

    "ItemOptions": {
      "Default": {
        "Content": "TextFormat:{0}",
        "Link": "QueryName:page"
        "InactiveBehavior": "Hide",
        "ActiveMode": "Always"
      },
      "GoToLastPage": {
        "Content": "Text:Go To Last Page"
      }
    }
  }

, added in my view.cshtml:
@addTagHelper *, Sakura.AspNetCore.Mvc.PagedList

and already added in the startup.cs:
services.Configure<PagerOptions>(Configuration.GetSection("Pager"));

What do i need to add to make it worked. I am currently using the v2.0.11.

Thanks

Sylvain

Simple pager usage issue

I have made all the required changes as per the guidance for simple usage of pager.
But seems like it does not consider the page number I click on instead considers the default one.
Can you please help me with this?

Checked attribute assignment in FlagsEnumInputTagHelper.cs

// Set checked attribute if (EnumFlagValue.HasFlag((Enum) EnumFlagFor.Model)) { output.Attributes.SetAttribute("checked", "checked"); }

This check should work opposite way:
// Set checked attribute if (EnumFlagFor.Model != null && ((Enum)EnumFlagFor.Model).HasFlag(EnumFlagValue)) { output.Attributes.SetAttribute("checked", "checked"); }

The TagHelperde problem was not resolved

items.First(i => i.Value == selectedValue).Selected = true; throw Exception "Sequence contains no matching element" in EnumTypeSelectTagHelper class。
Do you speek Chinese

DataAnnotationsLocalization cannot localize Enums

I use asp-enum-for tag attribute to display enums. but DataAnnotationsLocalization is not working on [Display(Name="ValueName")] attribute of each value. It displays only the initial text provided and it never changes by changing language or CurrentCulture.

ASP.NET Core 3.1
Visual Studio 2019 16.4.2

Adding additional attributes to the Pager

Thanks for all the hard work. I'm just not understanding I think. It looks like I should be able to add some additional tags to the the pager links, example: asp-route-customerId=3. I have several I want to add in the controller or in the top of the view for the first time the page is created with no existing query string items. It looks like once they are there all is good, If this is possible how could I do this? Thanks in advance.

Can I generate a custom url for setting-link-attr-data-ajax-url?

The pager is generating the href correctly and its working great.
I made a simple change to make ajax calls with the jquery ajax unobtrusive library and I made it work with a fixed button with the correct url.
So I am almost there, I only need to asign to the data-ajax-url parameter in the pager a custom url. It is almost the same as the href, but has an extra querystring for the handle that receives the call.
I tried to use your suggestion on #22, but I guess it only works for the item-default-link parameter and not for the data-ajax-url.
Do you have any ideas?
Thanks.

[Documentation] Localization needed for taghelpers

I guess it's been around since you fixed the language issue on the select taghelpers, but those wanting to use the select taghelpers without having localization anywhere else will have to add that in their startup file.

Since I don't consider that intuïtive I'm proposing to add it in the docs somewhere that you need to add the "services.AddLocalization();" in order for the taghelpers to work.

Sakura.AspNetCore doesnot contains defination of to ToPagedList<>

Error CS1061: 'IQueryable' does not contain a definition for 'ToPagedList' and no extension method 'ToPagedList' accepting a first argument of type 'IQueryable' could be found (are you missing a using directive or an assembly reference?) NETCoreApp,Version=v1.0

 public async Task<IActionResult> Index(int? page, int? pageSize)
        {
            int no = page ?? 1;
            int size = pageSize ?? 3;
            var data = from i in _context.Products select i;
            IPagedList<Products>lst= data.ToPagedList(size, no);
            return View(lst);
        }`

I have install package
"Sakura.AspNetCore.PagedList.Abstractions": "1.0.1",
"Sakura.AspNetCore.Mvc.PagedList": "2.0.2"
in my project

Example for paging with routes

Even though your documentation is quite extensive I wasn't unable to achieve the following.

I would like to use the pager for paging based on routes, e.g.

Default paging link: /index?page=3 (which is working fine)
desired outcome: /index/page/3

Unfortunately I wasn't able to do this maybe due to the fact that I didn't fully understand how to use the different link generators from your documentation.

Therefore I would be glad if you could tell me whether this is possible and if yes provide an example for this.
Thanks.

When in production, pager fails

When used in production on IIS and the path is something else than root, the paging functionality no longer works correctly. For example:

Suppose I have a site at http://root/path/controller/action and the next page should be http://root/path/controller/action?page=2. However, the link of the pager item will point to http://root/controller/action?page=2.

As you may have noticed, the path is missing from the link.
How would I configure the PagerItemOptions for this to work properly?

Sakura.AspNetCore ajax pager tag helper?

how to use ajax pager in AspNet core 1.0 ??
in RC1 i had done this , it worked.
<nav asp-pager="@Model" data-ajax-method="GET" data-ajax-update="#replace-search-data"></nav>

But
in AspNet core 1.0 I m Trying this but it doesnot work

<pager source="@Model" data-ajax="true" data-ajax-method="GET" data-ajax-update="#replace-search-data" />

Sakura.AspNetCore.Mvc.PagedList tag helper is not recognised

Hi,

I have encountered an error when following the instructions for implementing pagination.
It seems like it doesn't like when i add @addTagHelper *, Sakura.AspNetCore.Mvc.PagedList to _ViewImports.cs

Fyi, I am using .net core RC2. If someone can please advise if i am doing something wrong or if there is a bug.

Thank you

screen shot 2016-06-26 at 10 08 32 am

Invalid usage of the option NEXT in the FETCH statement

Good morning

I have been trying your plugin (latest version) for paging my search results but I am getting the following issue:

{System.Data.SqlClient.SqlException: Incorrect syntax near 'OFFSET'.
Invalid usage of the option NEXT in the FETCH statement.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
  ....

This is my code, everything worked well when I was using an IList:

            var pageNumber = 1; 
            var pageSize = 10;

            IQueryable<SearchResultViewModel> SearchVM = from item in _context.MyModel select new SearchResultViewModel()
                                                              {
                                                                A = item.a,
                                                                B= item.b
                                                            };


            model.SearchResults = SearchVM.ToPagedList(pageSize, pageNumber);
return model;

Thanks in advance for your input

S.

Query string with spaces issue

In version 2 of PagedList pager helper. Spaces in a existing query string are being encoded incorrectly. e.g

V1 Works fine
Category=All%20Categories&page=4
becomes Category=All Categories&page=4

V2 Does not work
Category=All%20Categories&page=4
becomes Category=All%252520Categories&page=4

VS2017, .NetCore.App 1.1.1 and Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadata error

Hello,
Using VS2015 with the latest tools, i was having the same error as #23 .

Considering that I was using VS2015 and it is now strongly advised to move to VS2017 with the recent stable releases, I migrated everything to VS2017, upgraded to the most recent SDK (1.0.3 corresponding to 1.0.4 LTS version and 1.1.1 current version of .NetCore App).
I have also checked that my Microsoft.AspNetCore.Mvc Nuget package was updated to 1.1.2.

Summary of my new csproj configuration file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <AssemblyTitle>Test</AssemblyTitle>
    <Authors>...</Authors>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <AssemblyName>test.Web</AssemblyName>
    <OutputType>Exe</OutputType>
    <PackageId>test.Web</PackageId>
    <RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
    <RuntimeFrameworkVersion>1.1.1</RuntimeFrameworkVersion>
    <PackageTargetFallback>$(PackageTargetFallback);dotnet5.6;portable-net45+win8</PackageTargetFallback>
  </PropertyGroup>

  <ItemGroup>
    <None Update="wwwroot\**\*">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\test.BLL\test.BLL.csproj" />
    <ProjectReference Include="..\test.DAL\test.DAL.csproj" />
    <ProjectReference Include="..\test.Services\test.Services.csproj" />
    <ProjectReference Include="..\test.Identity\test.Identity.csproj" />
    <ProjectReference Include="..\test.Validation\test.Validation.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
    <PackageReference Include="Sakura.AspNetCore.PagedList" Version="2.0.1" />
    <PackageReference Include="BundlerMinifier.Core" Version="2.4.337" />
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="1.0.1" />
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" />
    <PackageReference Include="FluentValidation.AspNetCore" Version="6.4.0" />
    <PackageReference Include="LinqKit.Microsoft.EntityFrameworkCore" Version="1.1.10" />
    <PackageReference Include="Sakura.AspNetCore.Mvc.PagedList" Version="2.0.12" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
  </ItemGroup>

  <Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
    <Exec Command="bower install" />
    <Exec Command="dotnet bundle" />
  </Target>

</Project>

All my packages are up-to-date, I am using the latest stable releases but I am still having this "An item with the same key has already been added. Key: Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadata" issue which appears for all my pages using IPagedList.

Am i doing something wrong?

Thank you

S.

TotalPage Maybe 0

Hi
totalPage Maybe 0 if get none record.please don't throw this exception.

if (this.TotalPage <= 0) throw new InvalidOperationException("The value of 'total-page' attribute must be positive integer."); if (this.CurrentPage <= 0 || this.CurrentPage > this.TotalPage) throw new InvalidOperationException("The value of 'current-page' attribute must between 1 and the value of 'total-page' attribute.");

Enums that don't inherit from int throw errors when attempting to bind

In our project we use enums that are inheriting from byte, but the FlagsEnumModelBinder and FlagsEnumModelBinderProvider only handle the case where the enum is of type int.

I've managed to get it to work as intended by checking the underlying enum type and then returning a model binder that matches that type.

FlagsEnumModelBinderProvider

public IModelBinder GetBinder([NotNull] ModelBinderProviderContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));

            if (IsNotFlagsEnum(context))
            {
                return null;
            }

            var enumType
                = Enum.GetUnderlyingType(context.Metadata.UnderlyingOrModelType);

            if (enumType == typeof(int))
            {
                return new FlagsEnumIntModelBinder();
            }
            if (enumType == typeof(byte))
            {
                return new FlagsEnumByteModelBinder();
            }
            if (enumType == typeof(short))
            {
                return new FlagsEnumShortModelBinder();
            }
            if (enumType == typeof(long))
            {
                return new FlagsEnumLongModelBinder();
            }

            throw new InvalidOperationException(
                $"enums inheriting of type '{enumType.FullName}' are not supporeted.");
        }

And then in each ModelBinder on the aggregate I change the cast to the expected type.
byte
var result = actualValues.Aggregate(0, (current, value) => (byte)(current | (byte)value));
short
var result = actualValues.Aggregate(0, (current, value) => (short)((short)current | (short)value));
long
var result = actualValues.Aggregate((long)0, (current, value) => (current | (long)value));

Ajax is not enabled until after I change another ajax element on the same page

I have found that when the pager loads, ajax isn't enabled straight away, and an incorrect href value is added (href="baseurl/review?page=2), so rather than loading a partial view, it loads the entire page again, within the partial. a working example is here http://cybrdude-001-site5.ftempurl.com/Review/ if you use the dropdown list, and select a value, it then reloads the partial, and the pager has the corect href (href="baseurl/GetReviewDetails?perPage=5&X-requested-with-XML.....) value and you can navigate.

The pager code is as follows
<pager id="pager1" class="pagination" setting-link-attr-data-ajax-update="#filter" setting-link-attr-data-ajax-mode="replace" setting-link-attr-data-ajax="true" />

I have tried adding the pager outside of the partial, but then it doesn't update with the new number of pages, and still has the wrong url.
I'm quite new to asp.net core and c# so I appologise in advance if this is user error

tagHelpers do not get used

Hi,

I've installed your tagHelper nuget and added references for the tagHelper library to _ViewImports.cshtml like this:

@using Sakura.AspNet.Mvc.TagHelpers
@addTagHelper "*, Sakura.AspNet.Mvc.TagHelpers"

and in my view use it like this:
<input type="checkbox" asp-flag-for="Options" asp-flag-value="MyOptions.Premium" class="form-control" />
but the renderer does not seem to pick it up. I can still see the (unresolved) asp-flags-for tags in the final html. I'm using Mvc 6.0.0-rc1.final. Is there anything else needed to make the tagHelpers work?

preserving current querystring in pager

Hello,
Thanks for the wonderful package you made for the community.
My question is regarding the pager taghelper as I use it in views with filtering(search) and sorting handled bt GET request. I read the demo and inspected the source code to find a way to preserve currentSearch and currentSort in pagers links. In the current package all querystring parameters are lost in the newly generated pages links.
example
this is how my view URL looks like
localhost/Products/?searchName=notebook&searchStatus=InStock&sort=Quantity_Desc
however in pager all links are like
localhost/Products/?page=1
localhost/Products/?page=2
(so all current search and sort are lost)
also i checked all-route-data but i could not find a solution because i want to append whats ever parameter included in URL to pager links

this article has one old implementation for pager if you can check or find a better one
http://www.itworld.com/article/2956575/development/how-to-sort-search-and-paginate-tables-in-asp-net-mvc-5.html
and this one made it generic without magicstrings (More practical)
https://codeutil.wordpress.com/2013/04/10/list-sort-edit-filter-in-asp-net-mvc-4/

one suggestion to PagerDemo.md
if you append this (FirstOrDefault) as many developers are not aware of to generate headers name in pagedlist

`









@foreach (var item in Model) {




}


@Html.DisplayNameFor(model => model.FirstOrDefault().ProductCode)

@Html.DisplayNameFor(model => model.FirstOrDefault().ProductName)

@Html.DisplayFor(modelItem => item.ProductCode)

@Html.DisplayFor(modelItem => item.ProductName)
`

Paging custom parameters

The custom parameter set by page label setting-tagname="C#" is invalid when paging, and the controller cannot get the tagname

need some code snippets for guiding.

I'm working on asp.net 5 for learning. before I want to write a paging tag, I found you have one, That's great. and have some comment just like title descripted.

【Document】The document is not up to date

EnumTypeSelectTagHelper.cs Does not support <select asp-enum-type="@typeof(ProjectAccessType)" name="AccessType"></select>,throw Exception“The object reference is not set to the object instance”。
Look at the source code asp-enum-value no set,But I don't want to set the default value。hope add isnull(EnumValueAttributeName)。
Finally, keep the document up to date。Thank you!
EnumTypeSelectTagHelper.cs现已不支持<select asp-enum-type="@typeof(ProjectAccessType)" name="AccessType"></select>方式,会出现“未将对象引用设置到对象实例”错误。
看源码发现是asp-enum-value未设置,但是我不想要设置默认值。希望可以对EnumValueAttributeName增加null判断,并更新下文档,
最后,请保持文档是最新的。谢谢!

Examples

I want to use your solution in my project, I look for paged list, but don't know what is the first step.
Could you please provide a few examples how to utilize your package?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.