Search code examples
c#jqueryvb.netstringbuilder

How to edit dynamically created HTML table using StringBuilder


I created a dynamic HTML table using StringBuilder. But when I am trying to pass it's cell value to jQuery Ajax call, I am not getting the correct values. How will I get the cell values after focus out?

Here's the exact code snippet:

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

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

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

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

Next

Return table.tostring ();

SaveVal Jquery method in .aspx file:

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");
}
});
}

I want to get this content editable cell value after focus out. SaveVal(id,cellvalue) function is defined in jQuery Ajax call and I want to pass these 2 parameters id and cellvalue which is the final value of the cell- if there is no edit then-existing value and if we edit and type new value then the new value will be passed.


Solution

  • First up get rid of the inline javascript, it is no longer best practice.

    Next, give your table an id or another way of identifying it (for my example I'm going to use an id of "MyTable".

    Then, as you've indicated jquery is in use, we will assign a jquery event handler.

    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");
        }
      });
    }