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; }
}