Giter VIP home page Giter VIP logo

mvc.jquery.datatables's Introduction

turn IQueryables into datagrids

Join the chat at https://gitter.im/mcintyre321/mvc.jquery.datatables

Install-Package Mvc.JQuery.DataTables

Install-Package Mvc.JQuery.DataTables.Templates *

Demo site Example

  • turn any IQueryable into a live datagrid. Tested with:
    • Linq To Objects
    • Entity Framework
    • Lucene.Net.Linq
  • wraps the very comprehensive jquery datatables plugin. Supported features:
    • Filtering (text, date or datetime range (with datepicker), number ranges, choose from dropdown, multiple values using checkboxes)
    • Sorting (configurable per column)
    • Paging (choose page size options, or fix them)
    • Customer column rendering
    • Custom positioning of filters (e.g. you could move them above the table)
    • Localization
    • TableTools support (PDF/Excel export)
    • Attribute based configuration (optional)
  • Can be run from dll

*skip this if using EmbeddedResourceVirtualPathProvider

See the test page and example project for info on how to use

http://nuget.org/packages/Mvc.JQuery.DataTables

The code here is based on code from http://code.google.com/p/datatables-asp-mvc/

Note to users

This library has been developed on an as-needed basis, so not all configuration settings from datatables are implemented yet. If you need a setting to be added, please fork the project, update the code, and update the example page to include a usage of the new setting (where this makes sense) e.g. https://github.com/mcintyre321/mvc.jquery.datatables/commit/c70f9c1f51178386e84a73ccea4495343f815012

If you have a feature request, bug, or a patch, please could you add an example page on a fork demonstrating the problem or feature. Thanks!

Flattr this git repo

If you have found this project useful, please consider contributing some documentation - it's the biggest weakness!

THANKS

To https://randomuser.me/ for the image thumbnails used in the example site

mvc.jquery.datatables's People

Contributors

abelozerov avatar athosxtreme avatar bitdeli-chef avatar chepix10 avatar curtisy1 avatar danmiser avatar draza67 avatar dreiundzwanzig avatar eyesnz avatar gitter-badger avatar jandic avatar juracy avatar kzhen avatar martimarkov avatar mcintyre321 avatar mcshaz avatar mrcsabatoth avatar offspringer avatar rallieon avatar raymens avatar seguemark avatar sohra avatar topkapi 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mvc.jquery.datatables's Issues

Timezone handling

Perhaps more of a question but how are timezones handled? It seems it's converting DateTime fields to local time, but DateTime? fields remain in UTC. Is it possible to simply leave all fields in UTC?

Have the DataTableVmHelper class respect ScaffoldColumn and DisplayName attributes

This is a simple version that works here:

    public static DataTableVm DataTableVmHelper<TController, TResult>(this HtmlHelper html, string id, Expression<Func<TController, DataTablesResult<TResult>>> exp, params Tuple<string, Type>[] columns)
    {
        if (columns == null || columns.Length == 0)
        {
            columns = 
                typeof(TResult).GetProperties()
                .Where(p => p.GetGetMethod() != null)
                .Where(p => p.GetCustomAttributes(typeof(ScaffoldColumnAttribute), false).Length == 0)
                .Select(p => p.GetCustomAttributes(typeof(DisplayNameAttribute), false).Length > 0 ?
                    Tuple.Create((p.GetCustomAttributes(typeof(DisplayNameAttribute), false)[0] as DisplayNameAttribute).DisplayName, p.PropertyType) :
                    Tuple.Create(p.Name, p.PropertyType)).ToArray();
        }

        var mi = exp.MethodInfo();
        var controllerName = typeof(TController).Name;
        controllerName = controllerName.Substring(0, controllerName.LastIndexOf("Controller"));
        var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
        var ajaxUrl = urlHelper.Action(mi.Name, controllerName);
        return new DataTableVm(id, ajaxUrl, columns);
    }

Exception thrown on simple code

Mvc.Jquery.Datatables version: 1.2.66

Products yields an empty set if that helps.

Code used:

var products = this.productRepository.GetAll();

return DataTablesResult.Create(products, dataTableParam, product => new ProductView()
{
    Name = product.Name
});

Exception:

{"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}
at System.ThrowHelper.ThrowArgumentOutOfRangeException()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at Mvc.JQuery.Datatables.DataTablesFilter.FilterPagingSortingSearch(DataTablesParam dtParameters, IQueryable data, ColInfo[] columns)
at Mvc.JQuery.Datatables.DataTablesResult`2.GetResults(IQueryable`1 data, DataTablesParam param)
at Mvc.JQuery.Datatables.DataTablesResult`2..ctor(IQueryable`1 q, DataTablesParam dataTableParam, Expression`1 transform)
at Mvc.JQuery.Datatables.DataTablesResult.Create[T,TRes](IQueryable`1 q, DataTablesParam dataTableParam, Expression`1 transform)
at PM.Web.Mvc.Controllers.ProductController.GetAllProducts(DataTablesParam dataTableParam) in g:\!Projects\Bestla.ProductManager\Solutions\PM.Web.Mvc\Controllers\ProductController.cs:line 41
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()

Get data method with parameters

Hi.

Is it possible to supply arguments to the method that is invoked to retrieve the data?

For instance if
public DataTablesResult GetUsers(DataTablesParam dataTableParam)
becomes
public DataTablesResult GetUsers(DataTablesParam dataTableParam, int type)

How can I make this call with the "type" parameter?
(HomeController h) => h.GetUsers(null)

I encountered this problem because I'm clicking a graphic's bar and I want to populate the datatable with the data from the bar which I'm clicking, so I need to pass an argument to my method.

Thank you.

DateTime? type

When I use a nullable type Datetime? in a class with variable value null, the column skipped in aaData and the entire row is displayed at the table shifted to the left by one position.

Templates

How to use templates???? Exist any manual about mvc.jquery.datatables for mvc????

Filtering Hidden Columns

Hello as a quick note thanks for fixing that formatting for DateTime types it was a big help.

Down to the issue I am facing. Using the latest version 1.2.92 from Nuget the ability to have filtering on a table that has multiple hidden fields does not work. The first hidden field that is used will negate the others there after.

For example if I create a model with four items the second being hidden (visible=false) but enable filtering on the last two the code below will not generate those filtering fields.

vm.FilterOn("CreatedDate", new { sSelector = "#datatables-created-date-range-filter" }).DateRange();
vm.FilterOn("StartDate", new { sSelector = "#datatables-start-date-range-filter" }).DateRange();

I am unsure if I am missing anything but have updated everything to reflect the latest version released (scripts, models, views, controllers). I was going to start poking through the changeset to see what the cause may be but thought I would throw this issue out in case.

Thanks

View Model(UserView) Sorting and Searching Problem

it's great codes.
when UserView model has different orders or more properties than User Model
there are sorting issue and IndexOutOfRangeException.
for example, if don't want to show Id in UserView and change orders of properties to show

public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

public class UserView
{
public string LastName { get; set; }
public string FirstName { get; set; }
}

public DataTablesResult GetUsers(DataTablesParam dataTableParam)
{
var users = Users().AsQueryable();

return DataTablesResult.Create(users, dataTableParam, user => new UserView()
{
    LastName = user.LastName,
    FirstName = user.FirstName
});

}

when sorting LastName column, it sorts User Model's Id Column.

DataTablesFilter::FilterPagingSortingSearch method get searchColumns which is User's columns.
dtParameters.sSearchColumns is actually UserView's columns.

I'm trying to fix it but don't know how to find columns mapping information between User and UserView.

Any Idea?

Now it selects all from database with entity models

when I used entity models with datatables before,
I checked with sql profiler and it actually generated paged sql queries.

Now after you changed the filtering to be done on the UserView,
when I use entity models, it selects all from the database then being paged and searched.

your changed code:

        var dataArray = data.Cast<T>().ToArray().AsQueryable().Select(_transform).Cast<TRes>().AsQueryable();
        dataArray = filters.FilterPagingSortingSearch(param, dataArray, out totalRecordsDisplay, searchColumns).Cast<TRes>();

"data.Cast().ToArray()" makes it select all from the database, i guess..
but it is beyond my programming knowledge to fix it.

Grid Not Showing

I Am trying to just get the grid to show, maybe there is something I am doing wrong, please help.

Code is posted below

Controller Code

using MyCPDtools.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using System.Web.Security;
using System.IO;
using Mvc.JQuery.Datatables;

namespace tools.Web.Controllers
{
[Authorize]
public class PageLinkController : Controller
{
ModelDb _db;

    public PageLinkController(ModelDb db)
    {
        _db = db;
    }

    public ActionResult Index()
    {
        return View();
    }

    public DataTablesResult<PageLinkView> GridIndex(DataTablesParam dataTableParam)
    {
        var pages = _db.PageLinks.Select(e => new PageLinkView(){
            AnchorItemClass = e.AnchorItemClass,
            DateCreated = e.DateCreated,
            DateUpdated = e.DateUpdated,
            Id = e.Id,
            PageName = e.PageName,
            ParentId = e.ParentId,
            SpanItemClass = e.SpanItemClass,
            UpdatedBy = e.UpdatedBy,
            Uri = e.Uri
        });

        return DataTablesResult.Create(pages, dataTableParam, page => new PageLinkView()
        {
            Id = page.Id,
            PageName = page.PageName,
            Uri = page.Uri
        });
    }

public class PageLinkView
{
public virtual int Id { get; set; }
public virtual int? ParentId { get; set; }
[DataTables(DisplayName="Page Name")]
public virtual string PageName { get; set; }
[DataTables(DisplayName= "Page Url")]
public virtual string Uri { get; set; }
public virtual string SpanItemClass { get; set; }
public virtual string AnchorItemClass { get; set; }
public virtual DateTime DateCreated { get; set; }
public virtual DateTime DateUpdated { get; set; }
public virtual string UpdatedBy { get; set; }
}
}

Html Code

@model List
@{Layout = null;}
@Html.DataTableIncludes(jqueryUi: true)
@Html.AntiForgeryToken()

<script src="~/Scripts/jquery-2.0.3.js"></script>
    <link href="~/Content/DataTables-1.9.4/media/css/demo_table.css" rel="stylesheet" />
    <script src="~/Scripts/DataTables-1.9.4/media/js/jquery.dataTables.js"></script>

</pre>
Create



</table>
@{Html.Partial("GridIndex", Html.DataTableVm("table-id", (PageLinkController p) => p.GridIndex(null)));}

No support for DateTime in dynamic linq

Hi,

I am trying to use this in my current assignment and working great but when I am having table with datetime column, search is causing problem in dynamic linq when it is going to find native method. I have attached the screenshot below for the problem. You can reproduce it by changing the datatype from DateTimeOffset to DateTime in your example project.

image

Performance affected when doing filtering on transformed data

Nice tool you have here. One suggestion is to create an alternative method that does not rely on filtering of transformed data.

An enterprise application will get major slow downs due to the fact that you execute an expression tree here private DataTablesData GetResults(IQueryable data, DataTablesParam param, Tuple<string, string, Type>[] searchColumns):

var filteredData = data.Select(_transform).AsQueryable();

rather than passing the filtering on to the datastore, filtering is done on the result set (linq to your transformed objects) from that executed query. If you have a lot of records this is a big hit on performance hit.

Something to think about

Demo donยดt search

Hi, My name is Claudinei and I from Brazil, Sรฃo Paulo.

Iยดm trying to search to full name and the example donยดt run. I donยดt found error. Can I help me, please?

Thanks,

Claudinei

aaData array does not contain model property names

Hello,
I'm using the latest mvc.jquery.datatables version 1.2.66. As far as I can see aaData now contains array of objects which have indexes as property names instead of model properties. Is there a way I can get property names or am I missed something.

Appreciate any help.

Extra "}" required for JsOptions.Add raw function

Was baffled by this for a while. In the example code...

vm.JsOptions.Add("fnCreatedRow", new Raw(@"function( nRow, aData, iDataIndex ) {
        $(nRow).attr('data-id', aData[0]);
      }
    }"));

there is an extra closing curly. Which gets stripped off in DataTableConfigVm.convertDictionaryToJsonBody()...

        private static string convertDictionaryToJsonBody(IDictionary<string, object> dict)
    {
        // Converting to System.Collections.Generic.Dictionary<> to ensure Dictionary will be converted to Json in correct format
        var dictSystem = new Dictionary<string, object>(dict);
        return JsonConvert.SerializeObject((object)dictSystem, Formatting.None, new RawConverter()).TrimStart('{').TrimEnd('}');
    }

Why is this?

Pluggable datasource and fluent column mappings

Rather than a rigid IQueryable dependency (for those of us not using something like entity framework) I was thinking of abstracting the data access a bit so you could plug in a method that would pass in appropriate parameters etc and fetch the necessary data.

Also, so as to not add dependency to my POCO's and to avoid a view model for the sole purpose of being able to columns/column attributes from anywhere.

I'm willing to fork/develop this stuff and re-submit it back as I'm going to need it anyway... just wondering if anyone else was interested in this functionality.

Searchable Columns

I haven't been able to figure out how to disable searching of a particular column.

I'm not a c# guru, but I know you can do this with bSearchable under aoColumnDefs in Datatables.

DataTablesResult bool values

bool members are returned as "True" or "False" strings instead true or false values. I resolved it adding this to DataTablesResult.PropertyTransformers declaration/instantiation:

Guard(s => s),

prior to:

Guard(o => (o ?? "").ToString())

Sorry, I think it should be the correct output and handle it's presentation on client side.

Add TR id from Serverside - implement fnCreatedRow

Im trying to add the ID field to the generated TRs of the DataTable but I dont know how. Using Javascript approach I can call fnCreatedRow and add the data to the specific TR but with mvc.jquery.datatables I cant access that callback and I cant find any other way of adding row ID to the TR from server side.

thanks!
Pablo

Mapping to viewmodel

Many MVC projects have a database model, and a view model mapped off the database view. mvc.jquery.datatables used to have a DataTables.Create method which would allow mapping - ie the return type was the return value of the transform function (last argument). This has been changed to return the type of the source. Similarly, there were tests in the testing framework to ensure this overload of the Create method worked. These tests have been removed! Is there a reason for this change? can/should it be rolled back to the (in my mind more useful) older Create method.

GetResults with IQueryable<T> using Linq to Entities is throwing Exception

It seems that there is an issue on Mvc.Jquery.Datables that doesn't allow the IQueryable instance that contains the entries, to be done using linq to entities (instead of linq to objects with enumerable).
The following exception is thrown:

System.NotSupportedException was unhandled by user code
  Message=Unable to cast the type 'Namespace.ResultRow' to type 'Namespace.ResultRow'. LINQ to Entities only supports casting Entity Data Model primitive types.
  Source=System.Data.Entity
  StackTrace:
       at System.Data.Objects.ELinq.ExpressionConverter.ValidateAndAdjustCastTypes(TypeUsage toType, TypeUsage fromType, Type toClrType, Type fromClrType)
       at System.Data.Objects.ELinq.ExpressionConverter.GetCastTargetType(TypeUsage fromType, Type toClrType, Type fromClrType, Boolean preserveCastForDateTime)
       at System.Data.Objects.ELinq.ExpressionConverter.CreateCastExpression(DbExpression source, Type toClrType, Type fromClrType)
       at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.CastMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
       at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
       at System.Data.Objects.ELinq.ExpressionConverter.Convert()
       at System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
       at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
       at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
       at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
       at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
       at System.Linq.EnumerableExecutor`1.ExecuteBoxed()
       at Mvc.JQuery.Datatables.DynamicLinq.DynamicQueryable.Count(IQueryable source)
       at Mvc.JQuery.Datatables.DataTablesFilter.FilterPagingSortingSearch(DataTablesParam dtParameters, IQueryable data, Int32& totalRecordsDisplay, Tuple`2[] columns)
       at Mvc.JQuery.Datatables.DataTablesResult`2.GetResults(IQueryable`1 data, DataTablesParam param, Tuple`2[] searchColumns)
       at Mvc.JQuery.Datatables.DataTablesResult`2..ctor(IQueryable`1 q, DataTablesParam dataTableParam, Func`2 transform)
       at Mvc.JQuery.Datatables.DataTablesResult.Create[T,TRes](IQueryable`1 q, DataTablesParam dataTableParam, Func`2 transform)

I've come up with the following fix:
Class: DataTablesResult.cs - Mvc.JQuery.Datatables.DataTablesResult
Method: private DataTablesData GetResults(IQueryable<T> data, DataTablesParam param, Tuple<string, Type>[] searchColumns)

Actual line 95:

    var dataArray = data.Cast<T>().Select(_transform).AsQueryable();

My fix is to remove the Cast to T of data:

    var dataArray = data.Select(_transform).AsQueryable();

The cast seems unnecessary since the variable data is already an IQueryable of T.

Can you please have look?
Thanks,
Bruno

Guidance requested

Hi Harry,
I have been banging my head against your helpers for the past few days. Is there a simple ASP.NET MVC app detailing the basic requirements?
I cannot get this type statement to execute:
@Html.Partial("DataTable", Html.DataTableVm("table-id", (HomeController h) => h.GetUsers(null)))

Any help would be greatly appreciated, thanks,
Kent

Date Format

Obviously more of a question than an issue, but is there a built in way to display a DateTime data type in a different format for example date only.

08/10/2013 4:00:00 PM ----> 08/10/2013

Thanks in advance, and also making a simple MVC interface into DataTables.

sEcho returning 0

I have a strange situation. In a master detail setup the master works but the detail is returning sEcho 0. The request send sEcho = 1. The only thing that is different is that the view model URL is not populated via the helper but it's static to llow query parameter:

var vm = Html.DataTableVm("table-id", Url.Action("example",new {id = idFromUrl}));

The response is never processed, that's what pointed me to check the sEcho value.

Any ideas ?

Server side processing search doesn't work

Hello!

I downloaded fresh version from GIT and run example project. After I wrote "a" letter into the search, exception pop up...

I'm trying to solve this problem but it looks like it's too much for an inexperienced developer like me. Any ideas? Leads?

Requested value 'a' was not found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Requested value 'a' was not found.

Source Error:

Line 8: {
Line 9: private static readonly Func<string, Type, object> ParseValue =
Line 10: (input, t) => t.IsEnum ? Enum.Parse(t, input) : Convert.ChangeType(input, t);
Line 11:
Line 12: internal static string FilterMethod(string q, List parametersForLinqQuery, Type type)

Source File: c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\TypeFilters.cs Line: 10

Stack Trace:

[ArgumentException: Requested value 'a' was not found.]
System.EnumResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument) +4054659
System.Enum.TryParseEnum(Type enumType, String value, Boolean ignoreCase, EnumResult& parseResult) +10736103
System.Enum.Parse(Type enumType, String value, Boolean ignoreCase) +78
System.Enum.Parse(Type enumType, String value) +6
Mvc.JQuery.Datatables.TypeFilters.<.cctor>b__3(String input, Type t) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\TypeFilters.cs:10
Mvc.JQuery.Datatables.TypeFilters.EnumFilter(String q, String columnname, Type type, List1 parametersForLinqQuery) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\TypeFilters.cs:172 Mvc.JQuery.Datatables.<>c__DisplayClass1.<Guard>b__0(String q, String c, Type t, List1 p) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\DataTablesFilter.cs:88
Mvc.JQuery.Datatables.<>c__DisplayClassc.b__5(ReturnedFilteredQueryForType f) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\DataTablesFilter.cs:101
System.Linq.WhereSelectListIterator2.MoveNext() +104 System.Linq.Enumerable.FirstOrDefault(IEnumerable1 source, Func2 predicate) +161 Mvc.JQuery.Datatables.<>c__DisplayClass9.<GetFilterClause>b__4(String queryPart) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\DataTablesFilter.cs:100 System.Linq.WhereSelectArrayIterator2.MoveNext() +66
System.Linq.WhereEnumerableIterator1.MoveNext() +85 System.Linq.Buffer1..ctor(IEnumerable1 source) +216 System.Linq.Enumerable.ToArray(IEnumerable1 source) +77
Mvc.JQuery.Datatables.DataTablesFilter.GetFilterClause(String query, ColInfo column, List1 parametersForLinqQuery) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\DataTablesFilter.cs:104 Mvc.JQuery.Datatables.DataTablesFilter.FilterPagingSortingSearch(DataTablesParam dtParameters, IQueryable data, ColInfo[] columns) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\DataTablesFilter.cs:20 Mvc.JQuery.Datatables.DataTablesResult2.GetResults(IQueryable1 data, DataTablesParam param) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\DataTablesResult.cs:109 Mvc.JQuery.Datatables.DataTablesResult2..ctor(IQueryable1 q, DataTablesParam dataTableParam, Expression1 transform) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\DataTablesResult.cs:73
Mvc.JQuery.Datatables.DataTablesResult.Create(IQueryable1 q, DataTablesParam dataTableParam, Expression1 transform) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables\DataTablesResult.cs:17
Mvc.JQuery.Datatables.Example.Controllers.HomeController.GetUsers(DataTablesParam dataTableParam) in c:\Users\Tom\Desktop\data tables novo\Mvc.JQuery.Datatables.Example\Controllers\HomeController.cs:33
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +214 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +253 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +21 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters) +191 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324 System.Web.Mvc.Controller.ExecuteCore() +106 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +91 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19 System.Web.Mvc.Async.<>c__DisplayClass81.b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.b__d() +48
System.Web.Mvc.SecurityUtil.b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9628700
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

DataTableResult.Create breaks pagination

The method seems to set iTotalDisplayRecords in the result to a wrong value so that the datatable will say:

Showing 1 to 10 of 10 entries (filtered from 100 total entries)

This can be seen in your own sample.

Cannot convert lamda expression to type ...

Hey!

I followed your example but i get in my few the following error:

Fehler 84 "lambda-Ausdruck" kann nicht in den Typ "System.Linq.Expressions.Expression<System.Func<Ren.CMS.Controllers.BackendHandlerContentController,Mvc.JQuery.Datatables.DataTablesResult<Ren.CMS.CORE.DataTables.BackendModels.ContentListView>>>" konvertiert werden, da dies kein Delegattyp ist. d:\Github\Ren.CMS.NET\Ren.CMS.Net\Source\Ren.CMS\Views\Backend\widgets\CONTENT_LIST\list.cshtml 205 99 Ren.CMS

Here is my code:
View:

var vm = Html.DataTableVm<BackendHandlerContentController, ContentListView>("tb", (BackendHandlerContentController c) => c.ContentList(null)); 

Controller:

   //
        // GET: /BackendHandlerContent/
        [HttpPost]
        [nPermissionVal(NeededPermissionKeys="USR_CAN_ENTER_BACKEND")]
        public DataTablesResult<ContentListView> ContentList( DataTablesParam dataTableParam)
        {
            List<ContentListView> _list = new List<ContentListView>();



            Ren.CMS.Content.ContentManagement.GetContent GC = new Content.ContentManagement.GetContent(new string[] { null }, String.Empty, locked: false, pageIndex:0, pageSize:0, contentRef: 0, countReferences: true, referenceContentTypes: null);

            List<Ren.CMS.Content.nContent> Contents = GC.getList();

            foreach (Ren.CMS.Content.nContent Con in Contents)
            {

                _list.Add(
                        new ContentListView()
                        {
                            Title = (Con.Texts.Any(e => e.LangCode == Ren.CMS.CORE.Helper.CurrentLanguageHelper.CurrentLanguage) ? Con.Texts.Where(e => e.LangCode == Ren.CMS.CORE.Helper.CurrentLanguageHelper.CurrentLanguage).FirstOrDefault().Title : Con.Texts.First().Title),
                            Creator = Con.CreatorName,
                            Category = Con.CategoryName,
                            cDate = Con.CreationDate

                        }


                    );

            }

            return  DataTablesResult.Create(_list.AsQueryable(), dataTableParam);
        }

Can anybody help me? :-)

Would be nice

Best

Malte

DataTableIncludes wrong path?

When site is running on a virtual directory,

@Html.DataTableIncludes(jqueryUi: false)

puts all the js files at the root, instead of the application root.

    public static IHtmlString DataTableIncludes(this HtmlHelper helper, bool jqueryUi = false, bool filters = true, bool tableTools = true)
    {
        StringBuilder output = new StringBuilder();
        Action<string> addJs = s => output.AppendLine(@"<script src=""" + s + @""" type=""text/javascript""></script>");
        Action<string> addCss = s => output.AppendLine(@"<link type=""text/css"" href=""" + s + @""" rel=""stylesheet""/>");

        addCss("/Content/DataTables-1.9.1/media/css/" + (jqueryUi ? ("jquery.dataTables_themeroller.css") : "jquery.dataTables.css"));
        addJs("/Scripts/DataTables-1.9.1/media/js/jquery.dataTables.js");
        if (filters) addJs("/Scripts/jquery.dataTables.columnFilter.js");
        if (tableTools)
        {
            addJs("/Scripts/DataTables-1.9.1/extras/TableTools/media/js/ZeroClipboard.js");
            addJs("/Scripts/DataTables-1.9.1/extras/TableTools/media/js/TableTools.js");
            addCss("/Content/DataTables-1.9.1/extras/TableTools/media/css/TableTools.css");
        }
        return helper.Raw(output.ToString());

    }

how do you fix this so that the HTML it builds should be the application root?

@Url.Content("~/" )

??

Exception when DisplayAttribute is set with unspecified Order property

DisplayAttribute.Order is really a nullable int so, if I we decorate a member with [Display(Name = "Foo")], TypeExtensions.GetSortedProperties will except.

I resolved it replacing this:

let order = ((da != null && da.Order != 0) ? da.Order : int.MaxValue)

with this:

let order = ((da != null && da.GetOrder() != null && da.GetOrder() >= 0) ? da.Order : int.MaxValue)

TypeFilters.StringFilter when null

Method is not controlling null strings, should be like this (and should be improved using string.format):

if (q.StartsWith("^"))
{
return "(!string.IsNullOrEmpty(" + columnname + ") && " + columnname + ".ToLower().StartsWith("" + q.ToLower().Replace(""", """") + ""))";
}
else
{
return "(!string.IsNullOrEmpty(" + columnname + ") && " + columnname + ".ToLower().Contains("" + q.ToLower().Replace(""", """") + ""))";
}

Using search box results in ')' or operator expected

When I use the search box in the example I get the below exception thrown.

If you could take a quick look that would be great :)

Mvc.JQuery.Datatables.DynamicLinq.ParseException was unhandled by user code
HResult=-2146233088
Message=')' or operator expected
Source=Mvc.JQuery.Datatables
Position=4
StackTrace:
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ValidateToken(TokenId t, String errorMessage) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 2406
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParseParenExpression(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 1239
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParsePrimaryStart(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 1149
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParsePrimary(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 1116
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParseUnary(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 1111
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParseMultiplicative(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 1058
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParseAdditive(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 1028
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParseComparison(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 945
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParseLogicalAnd(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 930
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParseLogicalOr(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 913
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.ParseExpression(Type resultType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 897
at Mvc.JQuery.Datatables.DynamicLinq.ExpressionParser.Parse(Type resultType, Type baseType) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 859
at Mvc.JQuery.Datatables.DynamicLinq.DynamicExpression.ParseLambda(ParameterExpression[] parameters, Type resultType, String expression, Type baseType, Object[] values) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 227
at Mvc.JQuery.Datatables.DynamicLinq.DynamicExpression.ParseLambda(Type itType, Type resultType, String expression, Type baseType, Object[] values) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 221
at Mvc.JQuery.Datatables.DynamicLinq.DynamicQueryable.Where(IQueryable source, String predicate, Object[] values) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DynamicLinq\DynamicLinq.cs:line 50
at Mvc.JQuery.Datatables.DataTablesFilter.FilterPagingSortingSearch(DataTablesParam dtParameters, IQueryable data, Int32& totalRecordsDisplay, Tuple2[] columns) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DataTablesFilter.cs:line 23 at Mvc.JQuery.Datatables.DataTablesResult2.GetResults(IQueryable q, DataTablesParam param, Tuple2[] searchColumns) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DataTablesResult.cs:line 97 at Mvc.JQuery.Datatables.DataTablesResult2..ctor(IQueryable1 q, DataTablesParam dataTableParam, Func2 transform) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DataTablesResult.cs:line 54
at Mvc.JQuery.Datatables.DataTablesResult.Create[T,TRes](IQueryable1 q, DataTablesParam dataTableParam, Func2 transform) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables\DataTablesResult.cs:line 15
at Mvc.JQuery.Datatables.Example.Controllers.HomeController.GetUsers(DataTablesParam dataTableParam) in C:\Users\Sam\Downloads\mcintyre321-mvc.jquery.datatables-b77d62b\mcintyre321-mvc.jquery.datatables-b77d62b\Mvc.JQuery.Datatables.Example\Controllers\HomeController.cs:line 32
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:

MvcHtmlString type sorting problem

Now sorting works perfect!!
but when I try sorting the MvcHtmlString type property which is UserView's Name property,
it throws ArgumentException "At least one object must implement IComparable."

Ability to specify default sorting

Hi,

thanks for a great library! It would be nice if there was an ability to specify what columns should be sorted first time the table is displayed. Possibly an extension of DataTables attribute?

Thanks

iTotalDisplayRecords Set Incorrectly

Based on the docs for DataTables, the 2 numbers passed back in a result are:

iTotalRecords - the total number of records without any filters/searches applied
iTotalDisplayRecords - the total number of records after filtering, before paging

Line 119 of DataTablesResult, however, uses this formula to calculate iTotalDisplayRecords:

iTotalDisplayRecords = filteredData.Count() + param.iDisplayStart,

This does not appear to be correct - why add iDisplayStart?

LINQ to Entities exception on search

Sorry, I get an exception using the search box:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

in Mvc.JQuery.Datatables.DynamicLinq.DynamicQueryable.Count(IQueryable source)
in Mvc.JQuery.Datatables.DataTablesFilter.FilterPagingSortingSearch(DataTablesParam dtParameters, IQueryable data, Int32&amp; totalRecordsDisplay, Tuple`2[] columns)
in Mvc.JQuery.Datatables.DataTablesResult`2.GetResults(IQueryable q, DataTablesParam param, Tuple`2[] searchColumns)
in Mvc.JQuery.Datatables.DataTablesResult`2..ctor(IQueryable`1 q, DataTablesParam dataTableParam, Func`2 transform)
in Mvc.JQuery.Datatables.DataTablesResult.Create[T,TRes](IQueryable`1 q, DataTablesParam dataTableParam, Func`2 transform)
in LizardSetup.Controllers.ResultController.GetResults(DataTablesParam dataTableParam) in (myfile.cs)

I installed the package with nuget, followed the sample ... the grid is working (paging, sorting) but using the seach box give the exception ...

Any info ? Thanks,
Best regards,
Luca

Support Resources for DisplayName Attribute

Hi,

My application has internazionalization using MVC resource files, and I can specify the Display attribute like this:

[Required]
[Display(Name = "resCategory", ResourceType = typeof(SAEiResource))]
public String Categoria { get; set; }

However DataTables seems to ignore the Display attribute and shows just the member name like "Categoria"

I know we can specify DisplayName with this decoration:

[DataTables(DisplayName = "Full Name")]
public string Name { get; set; }

But I dont know how to point to an entry of my Resource file like:

[DataTables(DisplayName = "Full Name", ResourceType = typeof(SAEiResource))]
public string Name { get; set; }

Is there any way of supporting internazionalization through resource files and applying it to DisplayNames in DataTables?

thanks!
Pablo

Case-insensitive search

Unlike client-side search, the one on server is always case-sensitive. The StringFilter defines it as follows:

"({0} != null && {0} != "" && ({0} == {1} || {0}.StartsWith({1}) || {0}.Contains({1})))"

Could you add in an optional parameter that would make the search case-insensitive.
Thanks.

Entity Framework queries not filtered in SQL

I've started playing around with this library today for the first time. I'm using Entity Framework 5 code first and I noticed that the query that goes off to the DB always fetches all records in the table, so it appears that the filtering and paging happens via Linq to Objects only after retrieving all records from the DB via EF. Is this by design, or is it suppose to filter via EF? Is DynamicLinq even compatible with EF?

Issues with encoding

Hello,

i have an issue with encoding. I followed the examples but german umlaute are displayed wrong (see image). Any ideas?

Kind regards
Andi

germanumlaute

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.