0
How to send via JSON
fields input
dynamically created, for example:
The user type in a text field number 4 and the function creates 8 input fields, or type 5 and the function creates 10 input fields, this function already works and is OK!.
This is the part of the function that creates the fields dynamically:
for (var i = 0; i < _qtde; i++) {
var new_date = new Date();
new_date.setMonth(new_date.getMonth() + i);
$("#divParcela").append("<div class='col-xs-6'> <label>Vencimento - parcela
" + parseInt(i + 1) + "</label> <input type='text' id='' value='" +
$.datepicker.formatDate('dd/mm/yy', new_date) + "' class='form-control' />
</div> <div class='col-xs-6'><label>Valor - parcela " + parseInt(i + 1) +
"</label><input type='text' id='' value='" + _valorParcela.toFixed(3) +
"' class='form-control' /></div>");
};
Then when you click the button Register, the system takes the values and sends via json
to the database, something like:
$("#btnCadastrar").on("click", function () {
var _movimentacao = {
"MovimentoFinanceiroID": $("#MovimentoFinanceiroID").val(),
"NumDocumento": $("#NumDocumento").val(),
"ItemMovimentoFinanceiro":[]
};
_movimentacao.ItemMovimentoFinanceiro.pusch({
"NumParcela": "Campo_Parcela_criado_dinamicamente",
"ValorDocumento": "Campo_Valor_criado_dinamicamente"
});
$.ajax({
url: "/MovimentoFinanceiro/IncluirJSON",
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
processData: false,
data: JSON.stringify(_movimentacao),
success: function (data) {
window.location.href = "/MovimentoFinanceiro/Index";
},
error: function (result) {
alert(result.responseText);
}
});
});
This is the Jsonresult method:
public JsonResult IncluirJSON(MovimentoFinanceiroViewModel pMovimentoFinanceiro)
{
try
{
//Aqui vou implementar rotina para gravar no banco de dados
return Json("OK", JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json("ERRO", JsonRequestBehavior.AllowGet);
}
}
These two classes are the intermediate model (DTO):
public class MovimentoFinanceiroViewModel
{
public List<ListDetalheMovimento> ListItens { get; set; }
}
public class ListDetalheMovimento
{
public decimal ValorParcela { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime? DataVencimentoParcela { get; set; }
}
Entity reflecting the database table:
public class MovimentoFinanceiro
{
[Key]
public int MovimentoFinanceiroID { get; set; }
public int ItemPlanoContabilID { get; set; }
public decimal ValorParcela { get; set; }
public DateTime DataVencimentoParcela { get; set; }
}
You need to do this by
json
same or can do for a normal POST? Maybe the Begincollectionitem can serve you.– Randrade
Yes, in that case it has to be
Json
– hard123