Grab a list from the View and move to the controller c#

Asked

Viewed 3,085 times

2

I have 2 lists that come from the database, one from technical and another from suppliers. I’m not able to take the View and pass to the Controller. And how to receive this list in the controller

inserir a descrição da imagem aqui

Follow the code:

Controller pass list to view as Viewbag

            var listaTecnicos = new BLL.Tecnico.TecnicoListar().ListarTecnicosProduto();
        ViewBag.listaTecnicos = listaTecnicos;

View Técnico

<table width="100%" class="table table-striped">
    <thead>
        <tr>
            <th>Cód.</th>
            <th>Técnico</th>
            <th>Quantidade</th>
            <th>Observação</th>
        </tr>
    </thead>
    <tbody>

        @{
            var cont = 0;

            for (int i = 0; i < ViewBag.listaTecnicos.Count; i++)
            {
                <tr class=".itemTecnico">
                    <td class="idTecnico">@ViewBag.listaTecnicos[i].ID_Tecnico</td>
                    <td>@ViewBag.listaTecnicos[i].Nome</td>
                    <td width="100px">@Html.TextBoxFor(model => model.QtdProdutoTecnico, new { id = "qtdProduto_" + cont, @class = "money2 form-control somarProdutoTecnico", maxlength = "5", @placeholder = "00,00" })</td>
                    <td>@Html.TextBoxFor(model => model.ObsProdutoTecnico, new { @class = "form-control" })</td>

                </tr>

                cont++;
            }
        }

    </tbody>
</table>

Javascript Jquery

    $('#btnSalvarTecnicos').click(function () {

    var arrayTecnicos = $('.itemTecnico');
    var idDoTecnico = new Array();
    var qtdDoTecnico = new Array();
    var obsDoTecncio = new Array();
    var todos_tecnicos = new Array();

    function pegarosTecnicos() {

        for (var i = 0; i < arrayTecnicos.length; i++) {

            todos_tecnicos = {
                idDoTecnico : $('.idTecnico').val(),
                qtdDoTecnico : $('.somarProdutoTecnico').val(),
                obsDoTecncio : $('.ObsTecnico').val()
            };
        };


    };


    $.ajax({
        url: '@Url.Action("SalvarTecnicos")', // to get the right path to controller from TableRoutes of Asp.Net MVC
        dataType: "json", //to work with json format
        type: "POST", //to do a post request
        contentType: 'application/json; charset=utf-8', //define a contentType of your request
        cache: false, //avoid caching results
        data: JSON.stringify(todos_tecnicos), // passar os parametros
        success: function (data) {


        },
        error: function (xhr) {
            alert("Erro! ao Salvar os com os tecnicos, Favor Entrar em Contato com O Suporte.");
        }


    });



});

Controlelr

    public ActionResult SalvarTecnicos(DTO.Produtos ListaTecncicos)
    {
      // aqui retorna ula lista vazia
    }
  • DTO Produto *

using System; using System.Collections.Generic; using System.Componentmodel;

namespace DTO { public class Products {

    public string QtdProdutoTecnico { get; set; }
    public string ObsProdutoTecnico { get; set; }
    public string QtdTotalTecnicos { get; set; }

    public List<DTO.Fornecedores> ListaFornecedoresProduto { get; set; }

    public List<DTO.Tecnicos> ListaTecncicos { get; set; }

    public List<DTO.ProdutoComTecnico> ProdutoComTecnico { get; set; }

} }

  • Hello Denilson, welcome to Stackoverflow. What exactly aren’t you able to do? Why can’t you take of View and go to the Controller? Explain your question further.

1 answer

1

Analyze this path:

public class Fornecedor
{
    public int ID { get; set; }
    public string Nome { get; set; }
    public List<Tecnico> Tecnico { get; set; }
}

public class Tecnico
{
    public int ID { get; set; }
    public int FornecedorID { get; set; }
    public string Nome { get; set; }
}

Usually in my Views (own use), my registration forms receive an DTO and an aggregated DTO list, according to the above structure.

In View I do the montage as follows.

@model Fornecedor

<div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
        <div class="form-group">
            @Html.LabelFor(model => model.Nome):
            @Html.ValidationMessageFor(model => model.Nome)
            @Html.TextBoxFor(model => model.Nome, new { @class = "form-control", maxlength = 50 })
        </div>
    </div>
</div>

@if (Model.Tecnico != null && Model.Tecnico.Count > 0)
{
    for (int i = 0; i < Model.Tecnico.Count; i++)
    {
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <div class="form-group">
                    @Html.HiddenFor(m => m.Tecnico[i].ID)
                    @Html.LabelFor(m => m.Tecnico[i].Nome):
                    @Html.ValidationMessageFor(m => m.Tecnico[i].Nome)
                    @Html.TextBoxFor(m => m.Tecnico[i].Nome, new { @class = "form-control", maxlength = 255 })
                </div>
            </div>
        </div>
    }
}

In Action here I mount as follows.

[HttpPost]
public ActionResult Cadastrar(Fornecedor pFornecedor)
{
    try
    {
        if (ModelState.IsValid)
        {

        }
        else
        {

        }
        return View();
    }
    catch (Exception ex)
    {
        return View();  
    }
}

When doing Submit the MVC will deliver the entire tree, one important thing is to keep the Dice sequentially, if you use Javascript to include items on the screen, the Dice must be redone (0, 1, 2, 3, etc).

It no longer includes code because it is from the basic structure assembly of ASP.NET MVC.

Assess if this form meets your needs.

  • it didn’t work out that well

  • Denilson, would have to see basically the concept used in the application, when it arrived in the controller, came the attached list? I have already developed some 5 applications using this concept and worked smoothly, as I said is a concept to be analyzed. Another detail is that here I deliver the content via post from the form of mvc @using (Ajax.Beginform(. I only use $.ajax when filling out combobox.

  • in my controller step to view a list of technician put in the description, there I am filling in the quantity and a description, I wanted to get this list with the Id_tecnico, Qtd, and the Description pass to the controller where I get this list to save in the bank.

Browser other questions tagged

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