在数据属性中显示对象

时间:2017-04-27 19:53:49

标签: javascript html5 custom-data-attribute

在我的Index.cshtml页面上,我有一张桌子:

<table>
  <thead>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
    <th></th>
  </thead>

  <tbody>
    @foreach(var item in Model)
    {
      <tr>
        <td>Test</td>
        <td>Subject</td>
        <td>100</td>
        <td><a href="#" data-personnel-id="@item.ID" data-personnel="@item" class="js-personnel-detail">Details</a></td>
      </tr>
    }
  </tbody>
</table>

我的目标是将item对象分配给数据属性,这样我就没有在它自己的数据属性中指定每个不同的对象属性。

当我尝试这个时,我在检查元素时得到了这个:

data-personnel="System.Data.Entity.DynamicProxies.Person_EA5AC055D1501E594DFBC8C0E360599F673410050ABB4A55BB0B191F6E442210"

data-personnel-id="7" ...所以我可以分配单个属性,但不能分配整个对象。

可以这样做吗?

2 个答案:

答案 0 :(得分:1)

使用JSON.NET ...

<div data-object='@JsonConvert.SerializeObject(item)'>

答案 1 :(得分:0)

试试这个:

data-personnel-id="@Model[item].ID" 

看起来foreach正在像JS foreach那样处理,其中项目实际上只是属性的名称,而不是值。