Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from a C# variable for datatables attribute

I fetch some values from an external source using a C# function (File.aspx.cs) and use this value as an custom attributes on datatables. However I only get 0,1,2 etc as the ID value and not the real value from the C# dataID variable, eventhough I already use var ID = '<%=dataID%>'; on my JS file (without quote I got error (JS) Expression expected).

How do I get this dataID value on my dt.file.js?

File.aspx.cs

public partial class Example : System.Web.UI.Page
{
    public static int dataID;

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static DataTableResponse GetList(string parameters)
    {
        DataTableAjaxPostModel model = JsonConvert.DeserializeObject<DataTableAjaxPostModel>(parameters);
        List<FieldAgentRow> list = new List<FieldAgentRow>();

        XmlDocument doc = Utilities.FileToXmlDocument("data");

        foreach (XmlNode person in doc.SelectNodes("//Personal"))
        {
            FieldAgentRow tmp = new FieldAgentRow();

            //other codes

            tmp.data_id = Int32.Parse(person.SelectSingleNode("ID").InnerText);
            dataID = tmp.data_id;

            list.Add(tmp);
        }

        DataTableResponse res = new DataTableResponse();
        res.draw = model.draw;
        res.data = list;

        return res;
    }
}

dt.file.js

$(document).ready(function () {
    var ID = '<%=dataID%>';
    var table = $('#list').DataTable({
        "createdRow": function (row, data, ID ) {
            $(row).attr('data-id', ID);
        }
        //other codes
    });

UPDATE SOLUTION: Thanks to Paul's answer, I am able to take the data_id value by modifying my JS code to:

$(document).ready(function () {
    var table = $('#list').DataTable({
        "createdRow": function (row, data, dataindex) {
            $(row).attr('data-id', data.data_id);
        }
        //other codes
    });
like image 436
user2018 Avatar asked Nov 30 '25 19:11

user2018


1 Answers

You need to use the data property to get to the json for the row in your createdRow method https://datatables.net/reference/option/createdRow. You should be able to do data.data_id (assuming the property name is not changed during serialization)..

You can also do console.log(data) there and examine it in your browser dev tools (f12) to see what properties are available.

like image 109
Paul Zepernick Avatar answered Dec 02 '25 08:12

Paul Zepernick