You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery DataTable中显示枚举的字符串值?

How to Display Enum String Values in DataTable

Hey there, let's work through this issue step by step. The core problem here is that your backend is sending enum values as integers when serialized, but you want the friendly string names (or display names) to show up in DataTable. There are two reliable ways to fix this—one on the backend, one on the frontend. Let's break them down:

This is the cleaner, more maintainable option because it centralizes the enum-to-string conversion. You won't have to duplicate enum mappings in the frontend, which avoids mismatches if your enum ever changes.

Option 1a: Use a DTO (Data Transfer Object)

Create a separate DTO class to shape the data you send to the frontend, converting the enum to its string representation explicitly:

// Define your DTO to match the data you want to display
public class RecordDto
{
    public int RequestID { get; set; }
    public string ProductName { get; set; }
    public string ProductCorporation { get; set; }
    public string ProductCategory { get; set; }
    // Add other fields from your Record class as needed
}

// Update your Controller action to use the DTO
public ActionResult GetData()
{
    using (Context c = new Context())
    {
        var recordList = c.Records.Select(r => new RecordDto
        {
            RequestID = r.RequestID,
            ProductName = r.ProductName,
            ProductCorporation = r.ProductCorporation,
            // Replace YourEnumType with your actual enum class name
            ProductCategory = Enum.GetName(typeof(YourEnumType), r.ProductCategory)
        }).ToList();
        
        return Json(new { data = recordList }, JsonRequestBehavior.AllowGet);
    }
}

Option 1b: Use Friendly Display Names (If You Have Custom Labels)

If your enum uses [Display(Name = "Friendly Label")] attributes, add an extension method to pull those friendly names instead of the raw enum string:

// Extension method to get the Display attribute name from an enum
public static string GetFriendlyName(this Enum enumValue)
{
    var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
    var displayAttr = fieldInfo.GetCustomAttribute<DisplayAttribute>();
    
    // Fall back to the enum string if no Display attribute exists
    return displayAttr?.Name ?? enumValue.ToString();
}

// Update the DTO mapping to use the extension method
ProductCategory = r.ProductCategory.GetFriendlyName()

Option 1c: Global Serialization Setting

If you want all enums in your app to serialize as strings by default, add this configuration to your Web.config:

<configuration>
  <system.web>
    <webServices>
      <jsonSerialization maxJsonLength="50000000">
        <converters>
          <add name="EnumConverter" type="Newtonsoft.Json.Converters.StringEnumConverter"/>
        </converters>
      </jsonSerialization>
    </webServices>
  </system.web>
</configuration>

With this, you won't need a DTO—your existing Record class will automatically serialize enums as strings.

Approach 2: Handle It on the Frontend

If you prefer to keep the backend unchanged, you can map enum integers to strings directly in DataTable's render function:

$(document).ready(function () {
    // Define a mapping of enum integers to their string names
    const productCategoryMap = {
        0: "Electronics",
        1: "Apparel",
        2: "Home Goods"
        // Add all your enum values and their corresponding strings here
    };

    dataTable = $("#requestTable").DataTable({
        "ajax": {
            "url": "/Request/GetData",
            "type": "GET",
            "datatype": "json"
        },
        "columns": [
            {
                "data": "RequestID",
                "render": function (data) {
                    return "<a class='btn btn-success btn-sm' onclick=PopupForm('@Url.Action("AddOrEdit","Request")/" + data + "')><i class='fa fa-edit'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-top:5px' onclick=Delete("+data+")><i class='fa fa-trash'></i> Delete</a>";
                },
                "orderable": false,
                "searchable": false,
                "width": "150px"
            },
            { "data": "ProductName" },
            { "data": "ProductCorporation" },
            { 
                "data": "ProductCategory",
                "render": function(data) {
                    // Return the matching string, or "Unknown" if no match exists
                    return productCategoryMap[data] || "Unknown";
                }
            },
        ],
        "language": {
            "emptyTable": "No data found, Please click on <b>Add New</b> Button"
        }
    });
});

Fixing Those Previous Errors

You mentioned hitting "Cannot set property 'data' of null" and "Invalid JSON response"—here's how to avoid those:

  • "Cannot set property 'data' of null":

    • Double-check your table has the correct id="requestTable" (no typos, no duplicate IDs on the page).
    • Ensure you load jQuery before DataTable's JS file—script order matters.
    • Confirm your DataTable initialization is fully wrapped in $(document).ready().
  • "Invalid JSON response":

    • This usually comes from circular references in your Record class (e.g., navigation properties pointing back to related entities). Using a DTO (Approach 1a) fixes this by only including the fields you need.
    • Alternatively, add reference loop handling to your Json result:
      return Json(new { data = recordList }, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }, JsonRequestBehavior.AllowGet);
      

内容的提问来源于stack exchange,提问作者Mona M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:47:40