javascript - 使用javascript从子表中获取名称值
问题描述
我有以下使用 JavaScript 的数据表,并希望找到一种可能的方法来获取 LineType Name 属性而不是“invoiceLineTypeId”列。存储 Name 属性的表是 InvoiceLineTypes 和相关的 ID。
我对 JavaScript 很陌生,但我的想法是我很可能必须渲染 invoiceLineTypeID 并对那个表进行某种类型的 jquery 查找,然后再显示回数据表中。关于我如何做到这一点的任何想法?
var table = $("#invoiceLineItems").DataTable({
ajax: {
url: "/api/InvoiceDetails/" + $('#InvoiceMaster_Id').val(),
dataSrc: ""
},
columns: [{
data: "invoiceLineTypeId"
}, {
data: "description"
}, {
data: "partNumber"
}, {
data: "quantity"
}, {
data: "chargeAmount"
}, {
data: "totalAmount"
}, {
data: "id",
render: function(data) {
return "<button class='btn-link js-delete' data-invoicedetails-id=" + data + ">Delete</button>";
}
}]
});
这是 InvoiceDetails 类
public class InvoiceDetails
{
public int Id { get; set; }
public DateTime DateCreated { get; set; }
public int AccountID { get; set; }
public Guid AccountGUID { get; set; }
public int SubAccountID { get; set; }
public int InvoiceId { get; set; }
public int CreatedBy { get; set; }
public InvoiceLineType InvoiceLineType { get; set; }
[Display(Name = "Line Type")]
public int InvoiceLineTypeId { get; set; }
public int Quantity { get; set; }
public decimal ChargeAmount { get; set; }
public decimal TotalAmount { get; set; }
public decimal AvgTotal { get; set; }
public string Description { get; set; }
public string PartNumber { get; set; }
}
解决方案
首先,您的 ajax 调用应该返回一个 json 数据,这非常重要。接下来,您可以根据需要使用后端为 json 填充键值对(例如:LineType 而不是 invoiceLineTypeId)。
此外,在 DataTable 中,您还可以利用列定义按索引号显示您喜欢的列。DataTable 的官方文档中有大量符合您要求的示例:datatables.net/manual/ajax