Skip to content
This repository was archived by the owner on Jan 8, 2024. It is now read-only.

Commit 249b2d2

Browse files
committed
Support custom request parameters
Provided support for custom request parameters, moved the internal class DataTablesRequest into a public DefaultDataTablesRequest which can be derived to provide aditional field/data and docs were updated with a sample settings a custom property.
1 parent c0f0073 commit 249b2d2

File tree

5 files changed

+158
-57
lines changed

5 files changed

+158
-57
lines changed

DataTables.Mvc/DataTables.Mvc.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@
7979
<Compile Include="DataTablesBinder.cs" />
8080
<Compile Include="DataTablesJsonBinder.cs" />
8181
<Compile Include="DataTablesResponse.cs" />
82+
<Compile Include="DefaultDataTablesRequest.cs" />
8283
<Compile Include="IDataTablesRequest.cs" />
8384
<Compile Include="NameValueCollectionExtensions.cs" />
8485
<Compile Include="Properties\AssemblyInfo.cs" />

DataTables.Mvc/DataTablesBinder.cs

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -71,16 +71,28 @@ public class DataTablesBinder : IModelBinder
7171
protected readonly string ORDER_DIRECTION_FORMATTING = "order[{0}][dir]";
7272
/// <summary>
7373
/// Binds a new model with the DataTables request parameters.
74+
/// You should override this method to provide a custom type for internal binding to procees.
7475
/// </summary>
75-
/// <param name="controllerContext"></param>
76-
/// <param name="bindingContext"></param>
77-
/// <returns></returns>
78-
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
76+
/// <param name="controllerContext">The context for the controller.</param>
77+
/// <param name="bindingContext">The context for the binding.</param>
78+
/// <returns>Your model with all it's properties set.</returns>
79+
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
80+
{
81+
return Bind(controllerContext, bindingContext, typeof(DefaultDataTablesRequest));
82+
}
83+
/// <summary>
84+
/// Binds a new model with both DataTables and your custom parameters.
85+
/// You should not override this method unless you're using request methods other than GET/POST.
86+
/// If that's the case, you'll have to override ResolveNameValueCollection too.
87+
/// </summary>
88+
/// <param name="controllerContext">The context for the controller.</param>
89+
/// <param name="bindingContext">The context for the binding.</param>
90+
/// <param name="modelType">The type of the model which will be created. Should implement IDataTablesRequest.</param>
91+
/// <returns>Your model with all it's properties set.</returns>
92+
protected virtual object Bind(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
7993
{
8094
var request = controllerContext.RequestContext.HttpContext.Request;
81-
var requestMethod = request.HttpMethod.ToLower();
82-
83-
var model = new DataTablesRequest();
95+
var model = (IDataTablesRequest)Activator.CreateInstance(modelType);
8496

8597
// We could use the `bindingContext.ValueProvider.GetValue("key")` approach but
8698
// directly accessing the HttpValueCollection will improve performance if you have
@@ -106,12 +118,23 @@ public object BindModel(ControllerContext controllerContext, ModelBindingContext
106118
ParseColumnOrdering(requestParameters, columns);
107119

108120
// Attach columns into the model.
109-
model.SetColumns(columns);
121+
model.Columns = new ColumnCollection(columns);
122+
123+
// Map aditional properties into your custom request.
124+
MapAditionalProperties(model, requestParameters);
110125

111126
// Returns the filled model.
112-
return (IDataTablesRequest)model;
127+
return model;
113128
}
114129
/// <summary>
130+
/// Map aditional properties (aditional fields sent with DataTables) into your custom implementation of IDataTablesRequest.
131+
/// You should override this method to map aditional info (non-standard DataTables parameters) into your custom
132+
/// implementation of IDataTablesRequest.
133+
/// </summary>
134+
/// <param name="requestModel">The request model which will receive your custom data.</param>
135+
/// <param name="requestParameters">Parameters sent with the request.</param>
136+
protected virtual void MapAditionalProperties(IDataTablesRequest requestModel, NameValueCollection requestParameters) { }
137+
/// <summary>
115138
/// Resolves the NameValueCollection from the request.
116139
/// Default implementation supports only GET and POST methods.
117140
/// You may override this method to support other HTTP verbs.
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#region COPYRIGHT(C) 2014 NACIONAL SOFT LTDA
2+
/*****************************************************************************
3+
{ }
4+
{ COPYRIGHT (C) 2013-2014 NACIONAL SOFT LTDA (CNPJ: 23.303.829/0001-69) }
5+
{ TODOS OS DIREITOS RESERVADOS. }
6+
{ +55 31 35050151 | [email protected] | BRASIL/BRAZIL }
7+
{ }
8+
{ ========================================================================== }
9+
{ ESTE TEXTO FOI ESCRITO SEM ACENTUACAO PROPOSITALMENTE }
10+
{ ========================================================================== }
11+
{ }
12+
{ TODO O CONTEUDO DESTE ARQUIVO E DE ARQUIVOS RELACIONADOS EH PROTEGIDO POR }
13+
{ LEIS BRASILEIRAS E INTERNACIONAIS DE DIREITOS AUTORAIS, SENDO VETADA SUA }
14+
{ DISTRIBUICAO, COMERCIALIZACAO, DIVULGACAO, ENGENHARIA-REVERSA OU QUALQUER }
15+
{ OUTRA FORMA DE DISPONIBILIZACAO, PARA QUAISQUER FINALIDADES, SEJA EM SUA }
16+
{ TOTALIDADE OU EM QUALQUER PARTE DE SEU CONTEUDO. }
17+
{ }
18+
{ AVISO DE DIREITOS AUTORAIS }
19+
{ ========================== }
20+
{ }
21+
{ ESTE CODIGO FONTE E TODOS OS ARQUIVOS INTERMEDIARIOS DELE RESULTANTES SAO }
22+
{ INTEIRAMENTE CONFIDENCIAIS E REPRESENTAM SEGREDO INDUSTRIAL E COMERCIAL DE }
23+
{ SUA PRODUTORA (NACIONAL SOFT LTDA). }
24+
{ }
25+
{ O CONTEUDO DESTE ARQUIVO E DE TODOS OS ARQUIVOS RELACIONADOS, EM TODO OU }
26+
{ EM PARTE, NAO PODERA SER COPIADO, TRANSFERIDO, COMERCIALIZADO, DISTRIBUIDO }
27+
{ OU DISPONIBILIZADO SOB QUALQUER FORMA SEM O PREVIO CONSENTIMENTO, POR }
28+
{ ESCRITO, DA NACIONAL SOFT LTDA, CONCEDENDO TODAS AS PERMISSOES NECESSARIAS }
29+
{ PARA TAL. }
30+
{ }
31+
{ O DESCUMPRIMENTO DESTE PODERA ACARRETAR AO INFRATOR OU EMPRESA RESPONSAVEL }
32+
{ PELA VIOLACAO OU AMBOS EM PROCESSOS CIVIS, CRIMINAIS, ADMINISTRATIVOS E DE }
33+
{ PERDAS FINANCEIRAS, TODOS EM SUA MAXIMA PENALIDADE, POR SER CONSIDERADO UM }
34+
{ CRIME DE VIOLACAO DE SEGREDO COMPETITIVO E FINANCEIRO DA PRODUTORA. }
35+
{ }
36+
{ AVISO AOS DESENVOLVEDORES DA NACIONAL SOFT }
37+
{ ========================================== }
38+
{ }
39+
{ MANTENHA-SE INFORMADO SOBRE AS RESTRICOES DE USO E POLITICAS DE SEGURANCA }
40+
{ DA EMPRESA. NAO REPASSE ESTE ARQUIVO A OUTROS, MESMO QUE SEJAM FUNCIONARI- }
41+
{ OS ATIVOS DA NACIONAL SOFT. NEM TODOS OS FUNCIONARIOS POSSUEM PERMISSAO DE }
42+
{ ACESSO AOS CODIGOS FONTES DE NOSSOS SISTEMAS. }
43+
{ }
44+
*****************************************************************************/
45+
#endregion COPYRIGHT(C) 2014 NACIONAL SOFT LTDA
46+
using System;
47+
using System.Collections.Generic;
48+
using System.Linq;
49+
using System.Text;
50+
using System.Threading.Tasks;
51+
52+
namespace DataTables.Mvc
53+
{
54+
/// <summary>
55+
/// Implements a default DataTables request.
56+
/// </summary>
57+
public class DefaultDataTablesRequest : IDataTablesRequest
58+
{
59+
/// <summary>
60+
/// Gets/Sets the draw counter from DataTables.
61+
/// </summary>
62+
public virtual int Draw { get; set; }
63+
/// <summary>
64+
/// Gets/Sets the start record number (jump) for paging.
65+
/// </summary>
66+
public virtual int Start { get; set; }
67+
/// <summary>
68+
/// Gets/Sets the length of the page (paging).
69+
/// </summary>
70+
public virtual int Length { get; set; }
71+
/// <summary>
72+
/// Gets/Sets the global search term.
73+
/// </summary>
74+
public virtual Search Search { get; set; }
75+
/// <summary>
76+
/// Gets/Sets the column collection.
77+
/// </summary>
78+
public virtual ColumnCollection Columns { get; set; }
79+
}
80+
}

DataTables.Mvc/IDataTablesRequest.cs

Lines changed: 10 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -39,62 +39,24 @@ namespace DataTables.Mvc
3939
public interface IDataTablesRequest
4040
{
4141
/// <summary>
42-
/// Gets the draw counter from client-side to give back on the server's response.
42+
/// Gets and sets the draw counter from client-side to give back on the server's response.
4343
/// </summary>
44-
int Draw { get; }
44+
int Draw { get; set; }
4545
/// <summary>
46-
/// Gets the start record number (count) for paging.
46+
/// Gets and sets the start record number (count) for paging.
4747
/// </summary>
48-
int Start { get; }
48+
int Start { get; set; }
4949
/// <summary>
50-
/// Gets the length of the page (max records per page).
50+
/// Gets and sets the length of the page (max records per page).
5151
/// </summary>
52-
int Length { get; }
52+
int Length { get; set; }
5353
/// <summary>
54-
/// Gets the global search pagameters.
54+
/// Gets and sets the global search pagameters.
5555
/// </summary>
56-
Search Search { get; }
56+
Search Search { get; set; }
5757
/// <summary>
58-
/// Gets the read-only collection of client-side columns with their options and configs.
58+
/// Gets and sets the read-only collection of client-side columns with their options and configs.
5959
/// </summary>
60-
ColumnCollection Columns { get; }
61-
}
62-
/// <summary>
63-
/// For internal use only.
64-
/// Represents DataTables request parameters.
65-
/// </summary>
66-
class DataTablesRequest : IDataTablesRequest
67-
{
68-
/// <summary>
69-
/// For internal use only.
70-
/// Gets/Sets the draw counter from DataTables.
71-
/// </summary>
72-
public int Draw { get; set; }
73-
/// <summary>
74-
/// For internal use only.
75-
/// Gets/Sets the start record number (jump) for paging.
76-
/// </summary>
77-
public int Start { get; set; }
78-
/// <summary>
79-
/// For internal use only.
80-
/// Gets/Sets the length of the page (paging).
81-
/// </summary>
82-
public int Length { get; set; }
83-
/// <summary>
84-
/// For internal use only.
85-
/// Gets/Sets the global search term.
86-
/// </summary>
87-
public Search Search { get; set; }
88-
/// <summary>
89-
/// For internal use only.
90-
/// Gets/Sets the column collection.
91-
/// </summary>
92-
public ColumnCollection Columns { get; private set; }
93-
/// <summary>
94-
/// For internal use only.
95-
/// Set the new columns on the mechanism.
96-
/// </summary>
97-
/// <param name="columns">The columns to be set.</param>
98-
public void SetColumns(IEnumerable<Column> columns) { Columns = new ColumnCollection(columns); }
60+
ColumnCollection Columns { get; set; }
9961
}
10062
}

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,42 @@ foreach(var column in sortedColumns)
6969
else { SortAgain(column.Data, column.SortDirection); }
7070
}
7171
```
72+
<h3>Is it possible to add custom parameters sent with my request?</h3>
73+
<p>
74+
Sure! It's a piece of cake now. Override <code>BindModel</code> and make it call <code>Bind</code> with your custom implementation of <code>IDataTablesRequest</code>.<br />
75+
Than, override the <code>MapAditionalProperties</code> to map your extra info into your custom type.<br />
76+
Here's a sample:
77+
</p>
78+
```C#
79+
// Create a custom type from DataTablesBinder.
80+
public class MyBinder : DataTablesBinder
81+
{
82+
// Override the default BindModel called by ASP.NET and make it call Bind passing the type of your
83+
// implementation of IDataTablesRequest:
84+
public override object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
85+
{
86+
return Bind(controllerContext, bindingContext, typeof(MyCustomRequest));
87+
}
88+
89+
// Override MapAditionalProperties so you can set your aditional data into the model:
90+
protected override void MapAditionalColumns(IDataTablesRequest requestModel, System.Collections.Specialized.NameValueCollection requestParameters)
91+
{
92+
var myModel = (MyCustomRequest)requestModel;
93+
myModel.MyCustomProp = Get<string>(requestParameters, "myCustomProp");
94+
}
95+
}
7296

97+
// You'll need a custom request model, of course.
98+
// Just derive from DefaultDataTablesRequest and you're fine :)
99+
// You can choose to implement IDataTablesRequest too, if you like.
100+
public class MyCustomRequest : DefaultDataTablesRequest
101+
{
102+
public string MyCustomProp { get; set; }
103+
}
104+
105+
// Than, on your controller/action, decorate with:
106+
public ActionResult MyActionResult([ModelBinder(typeof(MyBinder))] MyCustomRequest requestModel)
107+
```
73108
<h3>Any issues?</h3>
74109
<p>
75110
If you do find any issues, please, submit then and I'll fix it ASAP.

0 commit comments

Comments
 (0)