Dynamic Fields for Controller - ASP.NET MVC

1

I have this JavaScript which creates new fields for me when I need it and it makes the call to create JSON .

This counter within the adicionarCampos() function is required for something else regardless of what I need, even though it is not sequential as I wrote below:

function adicionarCampos(contador, botao) {

  var html = "Origem: <input type='number' name='Origem[" + contador + "]' />";
  html += "Destino: <input type='number' name='Destino[" + contador + "]' />";

  contador++;

  // Remove onclick 
  // Add onclick adicionarCampos(contador,$(this))
}

function formToJson(form) {
  var formArray = ($('#' + form).serializeArray())
  var returnArray = {};
  for (var i = 0; i < formArray.length; i++) {
    returnArray[formArray[i]['name']] = formArray[i]['value'];
  }

  alert(returnArray);

  $.ajax({
    type: "POST",
    url: "/Cadastrar",
    dataType: "json",
    data: returnArray,
    success: function(data) {}
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="form">
  <div id="camposNovos">

    // Estes novos campos virão aqui

  </div>
  <button type="button" onclick="formToJson(form)"> Cadastrar </button>
</form>

My Controller:

[HttpPost]
public JsonResult Cadastrar(....)
{}

What do I step inside Cadastrar() ? I have already tried string returnArray , object returnArray , string[] returnArray , object[] returnArray , all bring me null .

Is there another simpler way to pass this information from my form to JSON and then to controller ?

I have an object too:

public class JsonToObject
{
    public int Origem { get; set; }
    public int Destino { get; set; }
}
    
asked by anonymous 15.10.2018 / 17:16

2 answers

0

I would not recommend naming your inputs with the index together, particularly I would use the data-contador attribute for this ... but following your code, I could solve it as follows.

function adicionarCampos(contador, botao) {

  var html = "Origem: <input type='number' name='Origem[" + contador + "]' />";
  html += "Destino: <input type='number' name='Destino[" + contador + "]' />";

  contador++;

  // Remove onclick 
  // Add onclick adicionarCampos(contador,$(this))
}

function formToJson(form) {
  var formArray = ($('#' + form).serializeArray())
  var returnArray = {};
  for (var i = 0; i < formArray.length; i++) {
    returnArray[i] = { 
      Origem : $("input[name='Origem["+i+"]']").val(),
     Destino : $("input[name='Destino["+i+"]']").val()
    };
      
  }

  console.log(returnArray);
  
  //post comentado apenas para exibir o resultado no console
  /*
  $.ajax({
    type: "POST",
    url: "/Cadastrar",
    dataType: "json",
    data: returnArray,
    success: function(data) {}
  });*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="form">
  <div id="camposNovos">
    <!-- Exemplo de campos -->    
    Origem: <input type="number" name="Origem[0]" />    
    Destino: <input type="number" name="Destino[0]" />
    <br/>
    Origem: <input type="number" name="Origem[1]" />
    Destino: <input type="number" name="Destino[1]" />
    <br/>
    Origem: <input type="number" name="Origem[2]" />
    Destino:  <input type="number" name="Destino[2]" />
  </div>
  <br/>
  <button type="button" onclick="formToJson('form')"> Cadastrar </button>
</form>

In your controller you can receive this collection as follows

[HttpPost]
public JsonResult Cadastrar(List<JsonToObject> model)
{}
    
15.10.2018 / 18:53
0

If you are using a model you can do something like this:

<button type="button" onclick="formToJson('@Html.Raw(Json.Encode(Model))')"> Cadastrar </button>

Or try changing your "formToJson" function and see if it works:

function formToJson(form) {
  var formArray = JSON.stringify(jQuery('#' + form).serializeArray());
  var returnArray = {};
  for (var i = 0; i < formArray.length; i++) {
    returnArray[formArray[i]['name']] = formArray[i]['value'];
  }

  alert(returnArray);

  $.ajax({
    type: "POST",
    url: "/Cadastrar",
    dataType: "json",
    data: returnArray,
    success: function(data) {}
  });
}
    
15.10.2018 / 18:30