我的问题是,将主键放在桌面行上时的最佳做法是什么?使用Jquery查找ID。
因此,使用MVC,您可以使用编辑和创建数据创建数据表。删除按钮,单击时将打开模型弹出窗口。
你应该:
a)将主键放在每个按钮的数据属性中
b)每行都有隐藏字段
c)在每个按钮上使用Onclick&将ID传递给函数
d)在tr标签上有ID
答案 0 :(得分:1)
onclick
处理程序与jQuery一起使用(它将处理程序与代码分开,没有充分理由,它只支持单个处理程序)所以我倾向于使用选项e)
:
data-id=""
一次。然后从行中的任何元素我使用.closest('tr').data("id")
等来获取PK。 (实际上我使用这种模式,所以我经常使用自定义的jQuery扩展来实现这一点。例如:.closestAttr("data-id")
)。
<强> .closestAttr():强>
为感兴趣的人提供TypeScript代码:
// Find the nearest matching attribute in the elements themselves, as well as in all ancestors
jQuery.fn.closestAttr = function (attribute: string): string
{
return this.closest('[' + attribute + ']').attr(attribute);
};
或简单的JS:
// Find the nearest matching attribute in the elements themselves, as well as in all ancestors
jQuery.fn.closestAttr = function (attribute)
{
return this.closest('[' + attribute + ']').attr(attribute);
};
附加说明:如果数据在父级下分组,那么我在表上有另一个data-id=""
,代表父级FK /组等。
更新 - 有关评论中提供的代码示例:
我会这样做:
@foreach (var i in n)
{
<tr data-id="@i">
<td>@i</td>
<td><input type="button" class="edit" value="Edit" /></td>
<td><input type="button" class="delete" value="Delete" /></td>
</tr>
}
并从按下的按钮通过.closest('tr').data("id")
获取ID。
答案 1 :(得分:0)
如果您正在以真正的代码优先的方式工作,那么最好有一个专用于主键的唯一列。我假设您在问题中将列与Jquery中的按钮等同起来。这才是最好的。
当然,如果您使用的是预先存在的表,则必须使用该表中的密钥。有时它们是使用多个列的复杂键;我甚至看过一张表,其中所有列都用来形成一个键(但这是非常差的设计恕我直言)。
如果您负责数据库设计,那么在我看来,保留主键列总是值得的,特别是如果您使用的是SQL服务器。