简体   繁体   English

使用fnServerParams和aoData为jquery DataTable向服务器发送数据在MVC4中不起作用

[英]Sending data to the server with fnServerParams and aoData for jquery DataTable does not work in MVC4

I want to send extra data to serverside (ASP.Net MVC4) for my jquery datatable. 我想向我的jquery数据表发送额外的数据到服务器端(ASP.Net MVC4)。 There are many examples on how to this client side, but I can't get it to work on the serverside. 关于如何使用此客户端有很多示例,但是我无法在服务器端使用它。

Here's the code: 这是代码:

javascript: JavaScript的:

$(document).ready(function () {    
    var oTable = $('#myDataTable').dataTable({
        "bServerSide": true,
        "sAjaxSource": "SearchPatient/DataHandler",        
        "fnServerParams": function (aoData) {
            alert('in fnServerParams');
            aoData.push( { "name": "more_data", "value": "my_value" } );
        }

    });
});

Note: the alert goes off, so the function itself is working. 注意:警报关闭,因此该功能本身正在运行。

My model class: 我的模特班:

    /// <summary>
    /// Class that encapsulates most common parameters sent by DataTables plugin
    /// </summary>
    public class JQueryDataTableParamModel
    {
        /// <summary>
        /// fnServerparams, this should be an array of objects?
        /// </summary>        
        public object[] aoData { get; set; }

        /// <summary>
        /// Request sequence number sent by DataTable, same value must be returned in response
        /// </summary>       
        public string sEcho { get; set; }

        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string sSearch { get; set; }

        /// <summary>
        /// Number of records that should be shown in table
        /// </summary>
        public int iDisplayLength { get; set; }

        /// <summary>
        /// First record that should be shown(used for paging)
        /// </summary>
        public int iDisplayStart { get; set; }

        /// <summary>
        /// Number of columns in table
        /// </summary>
        public int iColumns { get; set; }

        /// <summary>
        /// Number of columns that are used in sorting
        /// </summary>
        public int iSortingCols { get; set; }

        /// <summary>
        /// Comma separated list of column names
        /// </summary>
        public string sColumns { get; set; }

        /// <summary>
        /// Text used for filtering
        /// </summary>
        public string oSearch { get; set; }

    }

and finally my Controller: 最后是我的控制器:

   public ActionResult DataHandler(JQueryDataTableParamModel param)
    {
        if (param.aoData != null)
        {
            // Get first element of aoData.  NOT working, always null              
            string lSearchValue = param.aoData[0].ToString();

            // Process search value
            // ....
        }


        return Json(new
        {                
            sEcho = param.sEcho,
            iTotalRecords = 97,
            iTotalDisplayRecords = 3,
            aaData = new List<string[]>() {
                new string[] {"1", "IE", "Redmond", "USA", "NL"},
                new string[] {"2", "Google", "Mountain View", "USA", "NL"},
                new string[] {"3", "Gowi", "Pancevo", "Serbia", "NL"}
                }
        },
        JsonRequestBehavior.AllowGet);
    }

Note: the action handler gets hit, so the ajax call to get data is also working and my datatable gets filled with 3 rows.. 注意:动作处理程序被击中,因此获取数据的ajax调用也正在工作,并且我的数据表填充了3行。

The problem is: aoData is always null. 问题是:aoData始终为空。 I expect the first element to hold "my_value". 我希望第一个元素保存“ my_value”。

Any help is much appreciated! 任何帮助深表感谢!

After searching for hours to find the answer finally posted it here. 经过几个小时的寻找答案,终于将其发布在这里。 Only to come up with the answer in minutes: 仅在几分钟内得出答案:

This does the trick: 这可以解决问题:

Add this line serverside in the DataHandler: 在DataHandler的服务器端添加以下行:

var wantedValue = Request["more_data"];

So the value is in the request and not in the model. 因此,值在请求中而不在模型中。

Thanks. 谢谢。

The value(s) are indeed in the model, but they are passed as individual fields, not as elements of aoData : 值确实在模型中,但是它们作为单独的字段而不是作为aoData元素aoData

public class JQueryDataTableParamModel {
    /// The "more_data" field specified in aoData
    public string more_data { get; set; }

    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; }
    public string oSearch { get; set; }
}

Usage: 用法:

public ActionResult DataHandler(JQueryDataTableParamModel param) {
    /// Reference the field by name, not as a member of aoData
    string lSearchValue = param.more_data;

    return Json( 
        new {                
            sEcho = param.sEcho,
            iTotalRecords = 97,
            iTotalDisplayRecords = 3,
            aaData = new List<string[]>() {
                new string[] {"1", "IE", "Redmond", "USA", "NL"},
                new string[] {"2", "Google", "Mountain View", "USA", "NL"},
                new string[] {"3", "Gowi", "Pancevo", "Serbia", "NL"}
            }
        },
        JsonRequestBehavior.AllowGet
    );
}

I will post another answer just to show a way to avoid code duplication. 我将发布另一个答案,只是为了展示一种避免代码重复的方法。

You can also make your JQueryDataTableParamModel as a base class for others. 您还可以将JQueryDataTableParamModel用作其他对象的基类。 Datatables will send the custom data in the same object , so you can't make the model bind it directly, unless your C# View Model matches exactly the DataTables sent object. 数据表将在同一对象中发送自定义数据,因此,除非您的C#视图模型与数据表发送的对象完全匹配,否则您无法使模型直接将其绑定。

This can be achieved as @SetFreeByTruth answered, but you could have some code duplication if you want it to be used in a whole project. 可以通过@SetFreeByTruth回答来实现,但是如果希望在整个项目中使用它,则可以进行一些代码重复。 This table has more_data , what if you have another table with only a property called custom_data ? 该表包含more_data ,如果您有另一个表仅具有一个名为custom_data的属性, custom_data怎么custom_data You would need to fill your object with multiple fields or create several datatables view models, each with your custom data. 您将需要用多个字段填充对象或创建几个数据表视图模型,每个模型都包含您的自定义数据。

For your scenario, you could use inheritance. 对于您的方案,可以使用继承。 Create a new class like this: 创建一个这样的新类:

//Inheritance from the model will avoid duplicate code
public class SpecificNewParamModel: JQueryDataTableParamModel
{
    public string more_data { get; set; }
}

Using it like this in a controller: 在控制器中像这样使用它:

public JsonResult ReportJson(SpecificNewParamModel Model)
{
    //code omitted code for clarity
    return Json(Return);
}

If you send the DataTables request and inspect the Model , you can see that it's filled with your custom data ( more_data ) and the usual DataTables data. 如果发送DataTables请求并检查Model ,则可以看到它充满了自定义数据( more_data )和常规DataTables数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM