c# - 模型绑定(bind)新的 Datatables 1.10 参数

标签 c# asp.net-mvc json datatables jquery-datatables

在 Datatables 1.10 中,ajax 服务器端参数从

public class DataTableParamModel
{ 
    public string sEcho{ get; set; }
    public string sSearch{ get; set; }
    public int iDisplayLength{ get; set; }
    public int iDisplayStart{ get; set; }
    public int iColumns{ get; set; }
    public int iSortingCols{ get; set; }
    public string sColumns{ get; set; }
}

到(API Here http://datatables.net/manual/server-side)

columns[i][data]    
columns[i][name]    
columns[i][orderable]
columns[i][search][regex]
columns[i][search][value]   
columns[i][searchable]  
...     
draw    
length  
order[i][column]    
order[i][dir]
... 
search[regex]
search[value]   
start

有些容易绑定(bind)

public class DataTableParamModel
{ 
    public string draw { get; set; }
    public int length{ get; set; }
    public int start { get; set; }
}

但新的数组格式看起来很棘手。

映射新参数格式的新合适模型是什么?

最佳答案

这是一个模型绑定(bind)器和将绑定(bind)这些新参数的类...

Nuget 包:https://www.nuget.org/packages/Wetware.DataTables

参数型号:

[ModelBinder(typeof(DTModelBinder))]
public class DTParameterModel
{
    /// <summary>
    /// Draw counter. This is used by DataTables to ensure that the Ajax returns from 
    /// server-side processing requests are drawn in sequence by DataTables 
    /// </summary>
    public int Draw { get; set; }

    /// <summary>
    /// Paging first record indicator. This is the start point in the current data set 
    /// (0 index based - i.e. 0 is the first record)
    /// </summary>
    public int Start { get; set; }

    /// <summary>
    /// Number of records that the table can display in the current draw. It is expected
    /// that the number of records returned will be equal to this number, unless the 
    /// server has fewer records to return. Note that this can be -1 to indicate that 
    /// all records should be returned (although that negates any benefits of 
    /// server-side processing!)
    /// </summary>
    public int Length { get; set; }

    /// <summary>
    /// Global Search for the table
    /// </summary>
    public DTSearch Search { get; set; }

    /// <summary>
    /// Collection of all column indexes and their sort directions
    /// </summary>
    public IEnumerable<DTOrder> Order { get; set; }

    /// <summary>
    /// Collection of all columns in the table
    /// </summary>
    public IEnumerable<DTColumn> Columns { get; set; }
}

/// <summary>
/// Represents search values entered into the table
/// </summary>
public sealed class DTSearch
{
    /// <summary>
    /// Global search value. To be applied to all columns which have searchable as true
    /// </summary>
    public string Value { get; set; }

    /// <summary>
    /// true if the global filter should be treated as a regular expression for advanced 
    /// searching, false otherwise. Note that normally server-side processing scripts 
    /// will not perform regular expression searching for performance reasons on large 
    /// data sets, but it is technically possible and at the discretion of your script
    /// </summary>
    public bool Regex { get; set; }
}

/// <summary>
/// Represents a column and it's order direction
/// </summary>
public sealed class DTOrder
{
    /// <summary>
    /// Column to which ordering should be applied. This is an index reference to the 
    /// columns array of information that is also submitted to the server
    /// </summary>
    public int Column { get; set; }

    /// <summary>
    /// Ordering direction for this column. It will be asc or desc to indicate ascending
    /// ordering or descending ordering, respectively
    /// </summary>
    public string Dir { get; set; }
}

/// <summary>
/// Represents an individual column in the table
/// </summary>
public sealed class DTColumn
{
    /// <summary>
    /// Column's data source
    /// </summary>
    public string Data { get; set; }

    /// <summary>
    /// Column's name
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Flag to indicate if this column is orderable (true) or not (false)
    /// </summary>
    public bool Orderable { get; set; }

    /// <summary>
    /// Flag to indicate if this column is searchable (true) or not (false)
    /// </summary>
    public bool Searchable { get; set; }

    /// <summary>
    /// Search to apply to this specific column.
    /// </summary>
    public DTSearch Search { get; set; }
}

模型绑定(bind)器:

/// <summary>
/// Model Binder for DTParameterModel (DataTables)
/// </summary>
public class DTModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        base.BindModel(controllerContext, bindingContext);
        var request = controllerContext.HttpContext.Request;
        // Retrieve request data
        var draw = Convert.ToInt32(request["draw"]);
        var start = Convert.ToInt32(request["start"]);
        var length = Convert.ToInt32(request["length"]);
        // Search
        var search = new DTSearch
        {
            Value = request["search[value]"],
            Regex = Convert.ToBoolean(request["search[regex]"])
        };
        // Order
        var o = 0;
        var order = new List<DTOrder>();
        while (request["order[" + o + "][column]"] != null)
        {
            order.Add(new DTOrder
            {
                Column = Convert.ToInt32(request["order[" + o + "][column]"]),
                Dir = request["order[" + o + "][dir]"]
            });
            o++;
        }
        // Columns
        var c = 0;
        var columns = new List<DTColumn>();
        while (request["columns[" + c + "][name]"] != null)
        {
            columns.Add(new DTColumn
            {
                Data = request["columns[" + c + "][data]"],
                Name = request["columns[" + c + "][name]"],
                Orderable = Convert.ToBoolean(request["columns[" + c + "][orderable]"]),
                Searchable = Convert.ToBoolean(request["columns[" + c + "][searchable]"]),
                Search = new DTSearch
                {
                    Value = request["columns[" + c + "][search][value]"],
                    Regex = Convert.ToBoolean(request["columns[" + c + "][search][regex]"])
                }
            });
            c++;
        }

        return new DTParameterModel
        {
            Draw = draw,
            Start = start,
            Length = length,
            Search = search,
            Order = order,
            Columns = columns
        };
    }
}

用法:

MyController.cs

public JsonResult DataTablesList(DTParameterModel model)
{
    ...
}

MVC6

如果您打算使用 MVC6,则不再需要模型绑定(bind)器,因为 MVC6 包含 JQueryFormValueProvider到可以绑定(bind)这些值的默认模型绑定(bind)器中。

不过,模型类本身可能仍然有用。

有一个bug在 2.1.0 中修复,不允许绑定(bind) HttpGet 但仍然适用于 HttpPost

关于c# - 模型绑定(bind)新的 Datatables 1.10 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502034/

相关文章:

c# - 发送电子邮件后如何通过 EWS 获取电子邮件 ConversationId

java - Spring REST - 手动解析@RequestBody中的JSON属性

java - 如何使用 Javascript 覆盖类型从 JSON 数组构建对象数组?

c# - 设置提取的YouTube视频的分辨率

c# - 使用HSQL进行.NET开发及流程相关问题

javascript - 在 Ajax 中同时传递 Json 对象和字符串值

c# - 将 System.ComponentModel.DisplayName 与动态值一起使用?

javascript - 试图解析一个包含多个数组的 json

c# - 如何使用 SAS token 通过 C# API 列出容器中的 Blob

c# - 由于缺少定义,在 .net Core 应用程序上构建失败