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

Commit

Permalink
Support custom request parameters
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ALMMa committed May 13, 2014
1 parent c0f0073 commit 249b2d2
Show file tree
Hide file tree
Showing 5 changed files with 158 additions and 57 deletions.
1 change: 1 addition & 0 deletions DataTables.Mvc/DataTables.Mvc.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
<Compile Include="DataTablesBinder.cs" />
<Compile Include="DataTablesJsonBinder.cs" />
<Compile Include="DataTablesResponse.cs" />
<Compile Include="DefaultDataTablesRequest.cs" />
<Compile Include="IDataTablesRequest.cs" />
<Compile Include="NameValueCollectionExtensions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
Expand Down
41 changes: 32 additions & 9 deletions DataTables.Mvc/DataTablesBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,16 +71,28 @@ public class DataTablesBinder : IModelBinder
protected readonly string ORDER_DIRECTION_FORMATTING = "order[{0}][dir]";
/// <summary>
/// Binds a new model with the DataTables request parameters.
/// You should override this method to provide a custom type for internal binding to procees.
/// </summary>
/// <param name="controllerContext"></param>
/// <param name="bindingContext"></param>
/// <returns></returns>
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
/// <param name="controllerContext">The context for the controller.</param>
/// <param name="bindingContext">The context for the binding.</param>
/// <returns>Your model with all it's properties set.</returns>
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
return Bind(controllerContext, bindingContext, typeof(DefaultDataTablesRequest));
}
/// <summary>
/// Binds a new model with both DataTables and your custom parameters.
/// You should not override this method unless you're using request methods other than GET/POST.
/// If that's the case, you'll have to override ResolveNameValueCollection too.
/// </summary>
/// <param name="controllerContext">The context for the controller.</param>
/// <param name="bindingContext">The context for the binding.</param>
/// <param name="modelType">The type of the model which will be created. Should implement IDataTablesRequest.</param>
/// <returns>Your model with all it's properties set.</returns>
protected virtual object Bind(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var request = controllerContext.RequestContext.HttpContext.Request;
var requestMethod = request.HttpMethod.ToLower();

var model = new DataTablesRequest();
var model = (IDataTablesRequest)Activator.CreateInstance(modelType);

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

// Attach columns into the model.
model.SetColumns(columns);
model.Columns = new ColumnCollection(columns);

// Map aditional properties into your custom request.
MapAditionalProperties(model, requestParameters);

// Returns the filled model.
return (IDataTablesRequest)model;
return model;
}
/// <summary>
/// Map aditional properties (aditional fields sent with DataTables) into your custom implementation of IDataTablesRequest.
/// You should override this method to map aditional info (non-standard DataTables parameters) into your custom
/// implementation of IDataTablesRequest.
/// </summary>
/// <param name="requestModel">The request model which will receive your custom data.</param>
/// <param name="requestParameters">Parameters sent with the request.</param>
protected virtual void MapAditionalProperties(IDataTablesRequest requestModel, NameValueCollection requestParameters) { }
/// <summary>
/// Resolves the NameValueCollection from the request.
/// Default implementation supports only GET and POST methods.
/// You may override this method to support other HTTP verbs.
Expand Down
80 changes: 80 additions & 0 deletions DataTables.Mvc/DefaultDataTablesRequest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#region COPYRIGHT(C) 2014 NACIONAL SOFT LTDA
/*****************************************************************************
{ }
{ COPYRIGHT (C) 2013-2014 NACIONAL SOFT LTDA (CNPJ: 23.303.829/0001-69) }
{ TODOS OS DIREITOS RESERVADOS. }
{ +55 31 35050151 | [email protected] | BRASIL/BRAZIL }
{ }
{ ========================================================================== }
{ ESTE TEXTO FOI ESCRITO SEM ACENTUACAO PROPOSITALMENTE }
{ ========================================================================== }
{ }
{ TODO O CONTEUDO DESTE ARQUIVO E DE ARQUIVOS RELACIONADOS EH PROTEGIDO POR }
{ LEIS BRASILEIRAS E INTERNACIONAIS DE DIREITOS AUTORAIS, SENDO VETADA SUA }
{ DISTRIBUICAO, COMERCIALIZACAO, DIVULGACAO, ENGENHARIA-REVERSA OU QUALQUER }
{ OUTRA FORMA DE DISPONIBILIZACAO, PARA QUAISQUER FINALIDADES, SEJA EM SUA }
{ TOTALIDADE OU EM QUALQUER PARTE DE SEU CONTEUDO. }
{ }
{ AVISO DE DIREITOS AUTORAIS }
{ ========================== }
{ }
{ ESTE CODIGO FONTE E TODOS OS ARQUIVOS INTERMEDIARIOS DELE RESULTANTES SAO }
{ INTEIRAMENTE CONFIDENCIAIS E REPRESENTAM SEGREDO INDUSTRIAL E COMERCIAL DE }
{ SUA PRODUTORA (NACIONAL SOFT LTDA). }
{ }
{ O CONTEUDO DESTE ARQUIVO E DE TODOS OS ARQUIVOS RELACIONADOS, EM TODO OU }
{ EM PARTE, NAO PODERA SER COPIADO, TRANSFERIDO, COMERCIALIZADO, DISTRIBUIDO }
{ OU DISPONIBILIZADO SOB QUALQUER FORMA SEM O PREVIO CONSENTIMENTO, POR }
{ ESCRITO, DA NACIONAL SOFT LTDA, CONCEDENDO TODAS AS PERMISSOES NECESSARIAS }
{ PARA TAL. }
{ }
{ O DESCUMPRIMENTO DESTE PODERA ACARRETAR AO INFRATOR OU EMPRESA RESPONSAVEL }
{ PELA VIOLACAO OU AMBOS EM PROCESSOS CIVIS, CRIMINAIS, ADMINISTRATIVOS E DE }
{ PERDAS FINANCEIRAS, TODOS EM SUA MAXIMA PENALIDADE, POR SER CONSIDERADO UM }
{ CRIME DE VIOLACAO DE SEGREDO COMPETITIVO E FINANCEIRO DA PRODUTORA. }
{ }
{ AVISO AOS DESENVOLVEDORES DA NACIONAL SOFT }
{ ========================================== }
{ }
{ MANTENHA-SE INFORMADO SOBRE AS RESTRICOES DE USO E POLITICAS DE SEGURANCA }
{ DA EMPRESA. NAO REPASSE ESTE ARQUIVO A OUTROS, MESMO QUE SEJAM FUNCIONARI- }
{ OS ATIVOS DA NACIONAL SOFT. NEM TODOS OS FUNCIONARIOS POSSUEM PERMISSAO DE }
{ ACESSO AOS CODIGOS FONTES DE NOSSOS SISTEMAS. }
{ }
*****************************************************************************/
#endregion COPYRIGHT(C) 2014 NACIONAL SOFT LTDA
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTables.Mvc
{
/// <summary>
/// Implements a default DataTables request.
/// </summary>
public class DefaultDataTablesRequest : IDataTablesRequest
{
/// <summary>
/// Gets/Sets the draw counter from DataTables.
/// </summary>
public virtual int Draw { get; set; }
/// <summary>
/// Gets/Sets the start record number (jump) for paging.
/// </summary>
public virtual int Start { get; set; }
/// <summary>
/// Gets/Sets the length of the page (paging).
/// </summary>
public virtual int Length { get; set; }
/// <summary>
/// Gets/Sets the global search term.
/// </summary>
public virtual Search Search { get; set; }
/// <summary>
/// Gets/Sets the column collection.
/// </summary>
public virtual ColumnCollection Columns { get; set; }
}
}
58 changes: 10 additions & 48 deletions DataTables.Mvc/IDataTablesRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,62 +39,24 @@ namespace DataTables.Mvc
public interface IDataTablesRequest
{
/// <summary>
/// Gets the draw counter from client-side to give back on the server's response.
/// Gets and sets the draw counter from client-side to give back on the server's response.
/// </summary>
int Draw { get; }
int Draw { get; set; }
/// <summary>
/// Gets the start record number (count) for paging.
/// Gets and sets the start record number (count) for paging.
/// </summary>
int Start { get; }
int Start { get; set; }
/// <summary>
/// Gets the length of the page (max records per page).
/// Gets and sets the length of the page (max records per page).
/// </summary>
int Length { get; }
int Length { get; set; }
/// <summary>
/// Gets the global search pagameters.
/// Gets and sets the global search pagameters.
/// </summary>
Search Search { get; }
Search Search { get; set; }
/// <summary>
/// Gets the read-only collection of client-side columns with their options and configs.
/// Gets and sets the read-only collection of client-side columns with their options and configs.
/// </summary>
ColumnCollection Columns { get; }
}
/// <summary>
/// For internal use only.
/// Represents DataTables request parameters.
/// </summary>
class DataTablesRequest : IDataTablesRequest
{
/// <summary>
/// For internal use only.
/// Gets/Sets the draw counter from DataTables.
/// </summary>
public int Draw { get; set; }
/// <summary>
/// For internal use only.
/// Gets/Sets the start record number (jump) for paging.
/// </summary>
public int Start { get; set; }
/// <summary>
/// For internal use only.
/// Gets/Sets the length of the page (paging).
/// </summary>
public int Length { get; set; }
/// <summary>
/// For internal use only.
/// Gets/Sets the global search term.
/// </summary>
public Search Search { get; set; }
/// <summary>
/// For internal use only.
/// Gets/Sets the column collection.
/// </summary>
public ColumnCollection Columns { get; private set; }
/// <summary>
/// For internal use only.
/// Set the new columns on the mechanism.
/// </summary>
/// <param name="columns">The columns to be set.</param>
public void SetColumns(IEnumerable<Column> columns) { Columns = new ColumnCollection(columns); }
ColumnCollection Columns { get; set; }
}
}
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,42 @@ foreach(var column in sortedColumns)
else { SortAgain(column.Data, column.SortDirection); }
}
```
<h3>Is it possible to add custom parameters sent with my request?</h3>
<p>
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 />
Than, override the <code>MapAditionalProperties</code> to map your extra info into your custom type.<br />
Here's a sample:
</p>
```C#
// Create a custom type from DataTablesBinder.
public class MyBinder : DataTablesBinder
{
// Override the default BindModel called by ASP.NET and make it call Bind passing the type of your
// implementation of IDataTablesRequest:
public override object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
{
return Bind(controllerContext, bindingContext, typeof(MyCustomRequest));
}

// Override MapAditionalProperties so you can set your aditional data into the model:
protected override void MapAditionalColumns(IDataTablesRequest requestModel, System.Collections.Specialized.NameValueCollection requestParameters)
{
var myModel = (MyCustomRequest)requestModel;
myModel.MyCustomProp = Get<string>(requestParameters, "myCustomProp");
}
}

// You'll need a custom request model, of course.
// Just derive from DefaultDataTablesRequest and you're fine :)
// You can choose to implement IDataTablesRequest too, if you like.
public class MyCustomRequest : DefaultDataTablesRequest
{
public string MyCustomProp { get; set; }
}

// Than, on your controller/action, decorate with:
public ActionResult MyActionResult([ModelBinder(typeof(MyBinder))] MyCustomRequest requestModel)
```
<h3>Any issues?</h3>
<p>
If you do find any issues, please, submit then and I'll fix it ASAP.
Expand Down

0 comments on commit 249b2d2

Please sign in to comment.