Pass data from an HTML table to the ASP.NET MVC controller

Asked

Viewed 2,730 times

3

I’m trying to pass data from an HTML table in my view to my Controller.
The data in this table are added dynamically. A Modal Bootstrap is opened, where the user informs some data, when clicked the button Ok, data is added to table via Javascript.
Until then, everything is working.
After all the data informed, I need to pass these to my controller to insert them in my BD.
There’s the problem!
I’ve tried many ways, but I haven’t got anything yet.
This is the code of my View that contains my table:

@model prjArqBuild.entidade_endereco
<div class="panel-group">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" href="#endereco">
                    Endereços
                </a>
            </h4>
        </div>
        <div id="endereco" class="panel-collapse collapse">
            <div class="panel-body">
                <table class="table" id="tabEndereco">
                    <thead>
                        <tr>
                            <th>
                                Endereco
                            </th>
                            <th>
                                Numero
                            </th>
                            <th>
                                Complemento
                            </th>
                            <th>
                                Bairro
                            </th>
                            <th>
                                Cidade
                            </th>
                            <th>
                                UF
                            </th>
                            <th>
                                CEP
                            </th>
                        </tr>
                    </thead>
                </table>
            </div>
            <div class="panel-footer">
                <p class="panel-title">
                    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#ModalEndereco">
                        Adicionar Endereço
                    </button>

                    <!-- Modal -->
                    <div class="modal fade" id="ModalEndereco" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                    <h4 class="modal-title" id="myModalLabel">Cadastro de Endereço</h4>
                                </div>
                                <div class="modal-body">
                                    <fieldset id="infoEndereco">
                                        <div class="row">
                                            <div class="col-md-8">
                                                @Html.EditorFor(model => model.een_endereco, new { htmlAttributes = new { @class = "form-control input-sm", placeholder = "Endereço" } })
                                                @Html.ValidationMessageFor(model => model.een_endereco, "", new { @class = "text-danger" })
                                            </div>
                                            <div class="col-md-4">
                                                @Html.EditorFor(model => model.een_numero, new { htmlAttributes = new { @class = "form-control input-sm", placeholder = "Numero" } })
                                                @Html.ValidationMessageFor(model => model.een_numero, "", new { @class = "text-danger" })
                                            </div>
                                        </div>
                                        <br />
                                        <div class="row">
                                            <div class="col-md-12">
                                                @Html.EditorFor(model => model.een_comple, new { htmlAttributes = new { @class = "form-control input-sm", placeholder = "Complemento" } })
                                                @Html.ValidationMessageFor(model => model.een_comple, "", new { @class = "text-danger" })
                                            </div>
                                        </div>
                                        <br />
                                        <div class="row">
                                            <div class="col-md-6">
                                                @Html.EditorFor(model => model.een_bairro, new { htmlAttributes = new { @class = "form-control input-sm", placeholder = "Bairro" } })
                                                @Html.ValidationMessageFor(model => model.een_bairro, "", new { @class = "text-danger" })
                                            </div>
                                            <div class="col-md-6">
                                                @Html.EditorFor(model => model.een_cidade, new { htmlAttributes = new { @class = "form-control input-sm", placeholder = "Cidade" } })
                                                @Html.ValidationMessageFor(model => model.een_cidade, "", new { @class = "text-danger" })
                                            </div>
                                        </div>
                                        <br />
                                        <div class="row">
                                            <div class="col-md-6">
                                                @Html.EditorFor(model => model.een_uf, new { htmlAttributes = new { @class = "form-control input-sm", placeholder = "Estado" } })
                                                @Html.ValidationMessageFor(model => model.een_uf, "", new { @class = "text-danger" })
                                            </div>
                                            <div class="col-md-6">
                                                @Html.EditorFor(model => model.een_cep, new { htmlAttributes = new { @class = "form-control input-sm", placeholder = "CEP" } })
                                                @Html.ValidationMessageFor(model => model.een_cep, "", new { @class = "text-danger" })
                                            </div>
                                        </div>
                                    </fieldset>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                                    <button id="addEndereco" type="button" OnClick="gravarDetalheEnd();" class="btn btn-primary">Salvar</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </p>
            </div>
        </div>
    </div>
</div>

This is my Javascript function that puts the data in the table dynamically:

function gravarDetalheEnd() {
            $('#tabEndereco tr:last').after('<tr><td>' + $('#een_endereco').val() + '</td><td>' + $('#een_numero').val() + '</td>' +
                '<td>' + $('#een_comple').val() + '</td>' + '<td>' + $('#een_bairro').val() + '</td>'
                + '<td>' + $('#een_cidade').val() + '</td>' + '<td>' + $('#een_uf').val() + '</td>'
                + '<td>' + $('#een_cep').val() + '</td></tr>');
        }

This is my way in Controller where I need to receive the data:

 public void AddEndereco(entidade_endereco entEnd)
        {
            db.entidade_endereco.Add(entEnd);
            db.SaveChanges();
        }

Note that I need to receive them as entidade_endereco
I tried to use several functions and 'AJAX' to pass it to the Controller, but without any answer.
Does anyone have any idea?

  • You want to send using Ajax or a request POST conventional?

1 answer

3

I may still be a young man padawan, but I would definitely use Json.

Well, first you need to quickly restructure your table, adding a class for example, to be able to get your data easier.

ATTENTION: You can ask here what would be the best way to structure your table to get the data, but this is not the focus of question and yes sending such data from View to the Controller.

See an example of how the table would look already with some data entered by the user:

<table id="tabEndereco" border="1">
  <tr class="cabecalho">
    <th>Endereco</th>
    <th>Numero</th>
    <th>Complemento</th>
    <th>Bairro</th>
    <th>Cidade</th>
    <th>UF</th>
    <th>CEP</th>
  </tr>
  <tr class="item">
    <td>Rua dos bobos</td>
    <td>0</td>
    <td>Casa engraçada</td>
    <td>Bairro do esmero</td>
    <td>Stacklândia</td>
    <td>SOpt</td>
    <td>0123-456</td>
  </tr>
  <tr class="item">
    <td>Rua dos sábios</td>
    <td>100</td>
    <td>Casa sem graça</td>
    <td>Bairro sem esmero</td>
    <td>Overflowlândia</td>
    <td>SOen</td>
    <td>6543-210</td>
  </tr>
</table>

To get this result, simply change its function gravarDetalheEnd() adding a class in tr.

Now let’s go to the best part! By clicking a button to send the data to the Controller (let’s call it btn-enviar) the following function shall be executed:

$("#btn-enviar").click(function(){
  var todos_enderecos = [];

  // Varrendo todos os itens inseridos (olha a vassoura!)
  $('.item').each(function() {

    // Montando objeto que possui as mesmas propriedades do objeto C# do Controller.
    var entidade_endereco = {
      endereco : $(this).children()[0].innerText,
      numero : $(this).children()[1].innerText,
      complemento: $(this).children()[2].innerText,
      bairro : $(this).children()[3].innerText,
      cidade: $(this).children()[4].innerText,
      uf : $(this).children()[5].innerText,
      cep : $(this).children()[6].innerText
    };

    // Adicionando objeto a lista.
    todos_enderecos.push(entidade_endereco);
  });

  // Após validações, chame a função que possui o Ajax para enviar a lista obtida.
  enviarDados(todos_enderecos);
});

Its function enviarDados would look similar to that:

function enviarDados(todos_enderecos){
   $.ajax({
      method: "POST",
      url: '@Url.Action("Action","Controller")',
      data: JSON.stringify(todos_enderecos)
   });
}

More about Ajax.

And in his Controller just create a method to receive a List<entidade_endereco>.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.