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

孤街醉人 提交于 2019-12-06 10:08:26

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:

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:

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. 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.

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. This table has more_data, what if you have another table with only a property called 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!