将参数从服务器对象传递到JavaScript的最佳方法

Dim*_*kiy 3 html javascript jquery unobtrusive-javascript asp.net-mvc-2

我渲染一个带有表格的视图.表的每一行都是可以编辑的对象.所以,这个表的最后一列有一堆"编辑"按钮.当单击其中一个EDIT按钮时,JavaScript函数必须选取当前行所表示的对象的Id.最后,我想最终得到一个干净的HTML:没有"onclick","onmouseover"属性,也没有自定义的属性.下面我有两个我不感兴趣的例子.有什么好主意吗?

例1:

View.aspx

<td>
  <input type="button" value="EDIT" onclick="JSFunction(<%: ObjectId %>)" />
</td>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

function JSFunction(id)
{
    //some code that does whatever with id
}
Run Code Online (Sandbox Code Playgroud)

例2:

View.aspx

<td>
  <input type="button" value="EDIT" customAttribute="<%: ObjectId %>" />
</td>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

$('input[type=button]').click(function() {
    var id = this.attr('customAttribute');
    //some code that does whatever with id
});
Run Code Online (Sandbox Code Playgroud)

PS如果你能想出一个更好的问题标题,请分享:)

Mar*_*man 6

我过去处理此问题的一种方法是使用html5数据属性.这是jQuery 1.4.3及更高版本的选择.

<table>
    <tr class="row" data-rowInfo='{"Id": "1", "Name": "Jon"}'>
        <td>
            Row Id 1
        </td>
        <td>
            <input type="button" value="Edit"/>
        </td>
    </tr>
    <tr class="row" data-rowInfo='{"Id": "2", "Name": "Mark"}'>
        <td>
            Row Id 2
        </td>
        <td>
            <input type="button" value="Edit"/>
        </td>
    </tr>
    <tfoot>
        <tr>
            <td></td>
        </tr>
    </tfoot>
</table>
Run Code Online (Sandbox Code Playgroud)

然后在您的jquery中,您可以执行以下操作:

$("input[type=button]").click(function(){
  var rowInfo = $(this).parents("tr.row").data("rowInfo");
  //Do something with rowInfo.Id;
});
Run Code Online (Sandbox Code Playgroud)

通过使用data属性,您可以拥有一个包含更多信息的丰富json对象,而不仅仅是一个属性.此外,您只需声明一个数据属性即可保存所有相关信息.

这个在jsfiddle上工作的例子.