Controller Dynamic Fields - ASP.NET MVC

Asked

Viewed 401 times

1

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

This counter within the function adicionarCampos() is necessary for something else regardless of what I need, even because 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>
<form id="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 I pass inside the Cadastrar()?
I’ve already tried string returnArray, object returnArray, string[] returnArray, object[] returnArray, everyone brings me null.

There is another simpler way to pass this information from my form to JSON and then to the controller?

I have an object too:

public class JsonToObject
{
    public int Origem { get; set; }
    public int Destino { get; set; }
}

2 answers

0

If you’re 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 make sure 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) {}
  });
}

0


I wouldn’t recommend you naming your inputs with the index together, particularly I would use the attribute data-contador for this... but following its code, could solve 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>
<form id="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)
{}

Browser other questions tagged

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