简体   繁体   English

保存 HTML 表格中的数据

[英]Save data from an HTML table

I am working with MVC and I am creating a dynamic table as data from @ Html.TextBoxFor is added that I have in my view, and all good so far我正在使用 MVC 并且我正在创建一个动态表,因为我添加了来自 @ Html.TextBoxFor 的数据,我认为到目前为止一切都很好

My question is: Any way to save my table that I create with a JS function?我的问题是:有什么办法可以保存我用 JS 函数创建的表?

Searching the web I found some examples but so far nothing works for me在网上搜索我找到了一些例子,但到目前为止没有任何东西对我有用

My Table我的桌子

<table id="mytable" class="table table-bordered table-hover ">
        <tr bgcolor="#90A8D0">
            <th>Proyecto</th>
            <th>Cuenta</th>
            <th>Sub Cuenta</th>
            <th>Beneficiario</th>
            <th>Tipo de Pago</th>
            <th>Pago en el proyecto</th>
            <th>Pago Por México</th>
            <th>Tarjeta Usuario</th>
            <th>Total de Remesa</th>
            <th>Obersvaciones</th>
            <th>Eliminar</th>

        </tr>
    </table>

So I create my dynamic table:所以我创建了我的动态表:

$(document).ready(function() {
    $('#adicionar').click(function () {
        debugger;
        var Proyecto = $("#ProyectoID option:selected").text();
        var Recurso = $("#RecursoID option:selected").text();
        var SubRecurso = $("#SubRecursoID option:selected").text();
        var Beneficiario =  document.getElementById("Beneficiario").value;
        var TipoPago = $("#TipoPagoID option:selected").text();
        var PagoProyecto = document.getElementById("PagoProyecto").value;
        var PagoMexico = document.getElementById("PagoMexico").value;
        var TarjetaUsuario = document.getElementById("TarjetaUsuario").value;
        var TotalRemesa =  parseInt(PagoProyecto) + parseInt(PagoMexico) + parseInt(TarjetaUsuario);
        var ObervacionesCuenta = document.getElementById("ObervacionesCuenta").value;
        var i = 1; //contador para asignar id al boton que borrara la fila
        var fila = '<tr id="row' + i + '"><td>' + Proyecto + '</td><td>' + Recurso + '</td><td>' + SubRecurso + '</td><td>' + Beneficiario + '</td><td>' + TipoPago + '</td><td>' + PagoProyecto + '</td><td>' + PagoMexico + '</td><td>' + TarjetaUsuario + '</td><td>' + TotalRemesa + '</td><td>' + ObervacionesCuenta + '</td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">Quitar</button></td></tr>'; //esto seria lo que contendria la fila

i++;

$('#mytable tr:first').after(fila);
$("#adicionados").text(""); //esta instruccion limpia el div adicioandos para que no se vayan acumulando
var nFilas = $("#mytable tr").length;
$("#adicionados").append(nFilas - 1);
//le resto 1 para no contar la fila del header
document.getElementById("Recurso").value ="";
document.getElementById("SubRecurso").value = "";
document.getElementById("Proyecto").value = "";
document.getElementById("Proyecto").focus();
});
$(document).on('click', '.btn_remove', function () {
var button_id = $(this).attr("id");
//cuando da click obtenemos el id del boton
$('#row' + button_id + '').remove(); //borra la fila
//limpia el para que vuelva a contar las filas de la tabla
$("#adicionados").text("");
var nFilas = $("#mytable tr").length;
$("#adicionados").append(nFilas - 1);
});
});

This is an example I found on the web:这是我在网上找到的一个例子:

$(function () {
debugger;
$('#mytable').each(function () {
var cuotaNo= $(this).find('td').eq(0).html();
var interes = $(this).find('td').eq(1).html();
var abonoCapital = $(this).find('td').eq(2).html();
var valorCuota = $(this).find('td').eq(3).html();
var saldoCapital = $(this).find('td').eq(4).html();

$.ajax({
 async: false,
 type: "POST",
 url: "../Guardardatos",
    data:"cuotaNo="+cuotaNo+"&interes="+interes+"&abonoCapital="+abonoCapital+"&valorCuota="+valorCuota+"&saldoCapital="+saldoCapital,
 data: {valores:valores},
 success: function(data) { if(data!="");}
});
});
});

As this last example is what I am trying to save the data that is created in my table因为最后一个例子是我试图保存在我的表中创建的数据

In this example, create TableView , TableRowView , and TableCellView classes.在此示例中,创建TableViewTableRowViewTableCellView类。 Each class returns an object with an element property and render* method.每个类都返回一个具有element属性和render*方法的对象。 TableView.element uses the table provided in your example. TableView.element使用您的示例中提供的表格。 TableRowView.element and TableCellView.element both create new elements. TableRowView.elementTableCellView.element都创建新元素。

After the data from the form (not shown in your example) is POSTED and the success callback is executed: first, create a new instance of TableView ;在表单中的数据(未在您的示例中显示)被发布并执行success回调之后:首先,创建一个新的TableView实例; second, create a new instance of TableRowView ;其次,创建一个新的TableRowView实例; third, create new instances of TableCellView for each data property, then render the property value inside of it.第三,为每个data属性创建新的TableCellView实例,然后在其中渲染属性值。

To ensure that the correct order of data elements is rendered, use columnOrder to define the table cell names, the iterate over them in the onSuccess callback.为确保呈现数据元素的正确顺序,请使用columnOrder定义表格单元格名称,并在onSuccess回调中对其进行迭代。 Each iteration, use the column name to access the corresponding data property.每次迭代,使用列名访问相应的data属性。

const columnOrder = [
  'proyecto', 
  'cuenta',
  'subCuenta',
  'beneficiario',
  'tipoPago',
  'pagoProyecto',
  'pagoMexico',
  'tarjetaUsuario',
  'totalRemesa',
  'obersvaciones',
  'elminar',
]
const TableView = () => {
  let table = document.getElementByID('myTable')
  return {
    element: table,
    renderTableRow: (element) => {
      this.element.appendChild(element)
      return this
    }
  }
}
const TableRowView = () => {
  let tr = document.createElement('tr')
  return {
    element: tr,
    renderTableCell: (element) => {
      this.element.appendChild(element)
      return this
    },
  }
}
const TableCellView = () => {
  let td = document.createElement('tr')
  return {
    element: td,
    render: (value) => {
      this.element.innerHTML = value
      return this
    },
  }
}
const onSuccess = (event) => {
  let data = event.data
  /*
    data
    -----
    {
      'proyecto': ??, 
      'cuenta': ??,
      'subCuenta': ??,
      'beneficiario': ??,
      'tipoPago': ??,
      'pagoProyecto': ??,
      'pagoMexico': ??,
      'tarjetaUsuario': ??,
      'totalRemesa': ??,
      'obersvaciones': ??,
      'elminar': ??,
    }
  */
  let table = new TableView()
  let row = new TableRow()
  columnOrder.forEach((columnName) => {
    let cell = new TableCellView()
    let cellData = data[columnName]
    cell.render(cellData)
    row.renderTableCell(cell.element)
    table.renderTableRow(row.element)
  })
}
$.ajax({
  ...,
  success: onSuccess,
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM