How to send via%% of% dynamically created% fields%, eg:
The user types in a text field the quantity 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 snippet 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>");
};
Next, when you click the Register button, the system takes the values and sends via JSON
to the database, it looks something like this:
$("#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 that reflects 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; }
}