首页 > 解决方案 > 如何使用 StringBuilder 编辑动态创建的 HTML 表

问题描述

我使用 StringBuilder 创建了一个动态 HTML 表。但是当我试图将它的单元格值传递给 jQuery Ajax 调用时,我没有得到正确的值。聚焦后如何获取单元格值?

这是确切的代码片段:

Dim table as new StringBuilder()
For each item in strategy

table.AppendLine(String.Format(“&lt;td>{0}</td>”,item.id);

table.AppendLine(“&lt;td>{0}</td>”,item.price);

table.AppendLine(“&lt;td contenteditable=“”true”” onfocusout =“SaveVal({0},{1})””&gt;{1}</td>”,item.id, item.cellvalue );

Next

Return table.tostring ();

.aspx 文件中的 SaveVal Jquery 方法:

function SaveVal(id,cellvalue){
$.ajax({
type:"POST",
url:"Maintenance.aspx/SaveVal",
contentType:"application/json;charset=utf-8",
dataType:"json",
data: JSON.stringify({
ids: id,
val:cellvalue
}),
async:false,
success:function(response){
alert("Value Saved");
}
});
}

我想在聚焦后获得这个内容可编辑的单元格值。SaveVal(id,cellvalue)函数是在 jQuery Ajax 调用中定义的,我想传递这两个参数idcellvalue这是单元格的最终值——如果没有编辑则现有值,如果我们编辑并键入新值,则将传递新值。

标签: c#jqueryvb.netstringbuilder

解决方案


首先摆脱内联javascript,这不再是最佳实践。

接下来,给您的表一个 id 或其他标识它的方式(在我的示例中,我将使用“MyTable”的 id。

然后,正如您所指出的,jquery 正在使用中,我们将分配一个 jquery 事件处理程序。

VB.net

Dim table as new StringBuilder()
For each item in strategy

'give this an identifiyer to explicitly find it in jQuery/javascript
table.AppendLine(String.Format("<td data-id>{0}</td>",item.id);

table.AppendLine("<td>{0}</td>",item.price);

'no more inline javascript 
table.AppendLine("<td contenteditable=""true"">{1}</td>",item.id, item.cellvalue );

Next

Return table.tostring ();

jQuery/javascript

$(document).ready(function(){
    /*Event handler for foucusout content edtitable cells in MyTable*/
    $("#MyTable [contenteditable=true]").on("focusout", function(){ 
       //Get ID
       let id = $(this).prevAll("[data-id]:first").text();
       //Get value of this cell
       let cellvalue = $(this).text();
       //Call your function, or just put its contents here
       SaveVal(id,cellvalue);
    });
});

function SaveVal(id,cellvalue){
  $.ajax({
    type:"POST",
    url:"Maintenance.aspx/SaveVal",
    contentType:"application/json;charset=utf-8",
    dataType:"json",
    data: JSON.stringify({
      ids: id,
      val:cellvalue
  }),
    async:false,
    success:function(response){
      alert("Value Saved");
    }
  });
}

推荐阅读